Spaces:
Sleeping
Sleeping
sanbo
commited on
Commit
·
5331238
1
Parent(s):
979bfc3
update sth. at 2025-01-16 22:21:25
Browse files
app.py
CHANGED
|
@@ -1,28 +1,15 @@
|
|
| 1 |
import asyncio
|
| 2 |
import logging
|
| 3 |
-
import time
|
| 4 |
import torch
|
| 5 |
import gradio as gr
|
| 6 |
-
from fastapi import FastAPI,
|
| 7 |
from fastapi.middleware.cors import CORSMiddleware
|
| 8 |
-
from pydantic import BaseModel
|
| 9 |
-
from transformers import AutoTokenizer, AutoModel
|
| 10 |
from typing import List, Dict
|
| 11 |
from functools import lru_cache
|
| 12 |
-
import numpy as np
|
| 13 |
import uvicorn
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
model_name: str = "jinaai/jina-embeddings-v3"
|
| 17 |
-
max_length: int = 512
|
| 18 |
-
batch_size: int = 32
|
| 19 |
-
host: str = "0.0.0.0"
|
| 20 |
-
port: int = 7860
|
| 21 |
-
enable_gpu: bool = True
|
| 22 |
-
queue_size: int = 100
|
| 23 |
-
|
| 24 |
-
class Config:
|
| 25 |
-
env_file = ".env"
|
| 26 |
|
| 27 |
class EmbeddingRequest(BaseModel):
|
| 28 |
input: str
|
|
@@ -33,13 +20,18 @@ class EmbeddingResponse(BaseModel):
|
|
| 33 |
embeddings: List[List[float]]
|
| 34 |
|
| 35 |
class EmbeddingService:
|
| 36 |
-
def __init__(self
|
| 37 |
-
self.
|
| 38 |
-
self.
|
|
|
|
|
|
|
|
|
|
| 39 |
self.model = None
|
| 40 |
self.tokenizer = None
|
| 41 |
-
self.request_queue = asyncio.Queue(maxsize=settings.queue_size)
|
| 42 |
self.setup_logging()
|
|
|
|
|
|
|
|
|
|
| 43 |
|
| 44 |
def setup_logging(self):
|
| 45 |
logging.basicConfig(
|
|
@@ -50,54 +42,53 @@ class EmbeddingService:
|
|
| 50 |
|
| 51 |
async def initialize(self):
|
| 52 |
try:
|
|
|
|
| 53 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 54 |
-
self.
|
| 55 |
trust_remote_code=True
|
| 56 |
)
|
| 57 |
self.model = AutoModel.from_pretrained(
|
| 58 |
-
self.
|
| 59 |
-
trust_remote_code=True
|
|
|
|
| 60 |
).to(self.device)
|
|
|
|
| 61 |
self.model.eval()
|
| 62 |
-
|
|
|
|
| 63 |
except Exception as e:
|
| 64 |
self.logger.error(f"模型初始化失败: {str(e)}")
|
| 65 |
raise
|
| 66 |
|
| 67 |
@lru_cache(maxsize=1000)
|
| 68 |
-
async def generate_embedding(self, text: str) ->
|
| 69 |
try:
|
| 70 |
inputs = self.tokenizer(
|
| 71 |
text,
|
| 72 |
return_tensors="pt",
|
| 73 |
truncation=True,
|
| 74 |
-
max_length=self.
|
| 75 |
-
|
|
|
|
| 76 |
|
| 77 |
with torch.no_grad():
|
| 78 |
outputs = self.model(**inputs).last_hidden_state.mean(dim=1)
|
| 79 |
-
return outputs.
|
| 80 |
except Exception as e:
|
| 81 |
self.logger.error(f"生成嵌入向量失败: {str(e)}")
|
| 82 |
raise
|
| 83 |
|
| 84 |
-
|
| 85 |
-
if not text.strip():
|
| 86 |
-
raise ValueError("输入文本不能为空")
|
| 87 |
-
return await self.generate_embedding(text)
|
| 88 |
-
|
| 89 |
-
# 初始化服务
|
| 90 |
-
settings = Settings()
|
| 91 |
-
embedding_service = EmbeddingService(settings)
|
| 92 |
-
|
| 93 |
-
# FastAPI应用
|
| 94 |
app = FastAPI(
|
| 95 |
title="Jina Embeddings API",
|
| 96 |
description="Text embedding generation service using jina-embeddings-v3",
|
| 97 |
version="1.0.0"
|
| 98 |
)
|
| 99 |
|
| 100 |
-
#
|
|
|
|
|
|
|
|
|
|
| 101 |
app.add_middleware(
|
| 102 |
CORSMiddleware,
|
| 103 |
allow_origins=["*"],
|
|
@@ -106,7 +97,7 @@ app.add_middleware(
|
|
| 106 |
allow_headers=["*"],
|
| 107 |
)
|
| 108 |
|
| 109 |
-
#
|
| 110 |
@app.post("/generate_embeddings", response_model=EmbeddingResponse)
|
| 111 |
@app.post("/api/v1/embeddings", response_model=EmbeddingResponse)
|
| 112 |
@app.post("/hf/v1/embeddings", response_model=EmbeddingResponse)
|
|
@@ -114,13 +105,11 @@ app.add_middleware(
|
|
| 114 |
@app.post("/hf/v1/chat/completions", response_model=EmbeddingResponse)
|
| 115 |
async def generate_embeddings(request: EmbeddingRequest):
|
| 116 |
try:
|
| 117 |
-
embedding = await embedding_service.
|
| 118 |
return EmbeddingResponse(
|
| 119 |
status="success",
|
| 120 |
-
embeddings=embedding
|
| 121 |
)
|
| 122 |
-
except ValueError as e:
|
| 123 |
-
raise HTTPException(status_code=400, detail=str(e))
|
| 124 |
except Exception as e:
|
| 125 |
raise HTTPException(status_code=500, detail=str(e))
|
| 126 |
|
|
@@ -128,18 +117,18 @@ async def generate_embeddings(request: EmbeddingRequest):
|
|
| 128 |
async def root():
|
| 129 |
return {
|
| 130 |
"status": "active",
|
| 131 |
-
"model":
|
| 132 |
-
"device": embedding_service.device,
|
| 133 |
-
"
|
| 134 |
}
|
| 135 |
|
| 136 |
# Gradio界面
|
| 137 |
def gradio_interface(text: str) -> Dict:
|
| 138 |
try:
|
| 139 |
-
embedding = asyncio.run(embedding_service.
|
| 140 |
return {
|
| 141 |
"status": "success",
|
| 142 |
-
"embeddings": embedding
|
| 143 |
}
|
| 144 |
except Exception as e:
|
| 145 |
return {
|
|
@@ -153,10 +142,7 @@ iface = gr.Interface(
|
|
| 153 |
outputs=gr.JSON(label="嵌入向量结果"),
|
| 154 |
title="Jina Embeddings V3",
|
| 155 |
description="使用jina-embeddings-v3模型生成文本嵌入向量",
|
| 156 |
-
examples=[
|
| 157 |
-
["这是一个测试句子。"],
|
| 158 |
-
["人工智能正在改变世界。"]
|
| 159 |
-
]
|
| 160 |
)
|
| 161 |
|
| 162 |
@app.on_event("startup")
|
|
@@ -164,15 +150,17 @@ async def startup_event():
|
|
| 164 |
await embedding_service.initialize()
|
| 165 |
|
| 166 |
if __name__ == "__main__":
|
| 167 |
-
#
|
| 168 |
asyncio.run(embedding_service.initialize())
|
| 169 |
|
| 170 |
-
#
|
| 171 |
gr.mount_gradio_app(app, iface, path="/ui")
|
| 172 |
|
|
|
|
| 173 |
uvicorn.run(
|
| 174 |
app,
|
| 175 |
-
host=
|
| 176 |
-
port=
|
| 177 |
-
workers=1
|
|
|
|
| 178 |
)
|
|
|
|
| 1 |
import asyncio
|
| 2 |
import logging
|
|
|
|
| 3 |
import torch
|
| 4 |
import gradio as gr
|
| 5 |
+
from fastapi import FastAPI, HTTPException
|
| 6 |
from fastapi.middleware.cors import CORSMiddleware
|
| 7 |
+
from pydantic import BaseModel
|
|
|
|
| 8 |
from typing import List, Dict
|
| 9 |
from functools import lru_cache
|
|
|
|
| 10 |
import uvicorn
|
| 11 |
+
import psutil
|
| 12 |
+
import numpy as np
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 13 |
|
| 14 |
class EmbeddingRequest(BaseModel):
|
| 15 |
input: str
|
|
|
|
| 20 |
embeddings: List[List[float]]
|
| 21 |
|
| 22 |
class EmbeddingService:
|
| 23 |
+
def __init__(self):
|
| 24 |
+
self.model_name = "jinaai/jina-embeddings-v3"
|
| 25 |
+
self.max_length = 512
|
| 26 |
+
self.batch_size = 8
|
| 27 |
+
self.device = torch.device("cpu")
|
| 28 |
+
self.num_threads = min(psutil.cpu_count(), 4) # 限制CPU线程数
|
| 29 |
self.model = None
|
| 30 |
self.tokenizer = None
|
|
|
|
| 31 |
self.setup_logging()
|
| 32 |
+
|
| 33 |
+
# CPU优化配置
|
| 34 |
+
torch.set_num_threads(self.num_threads)
|
| 35 |
|
| 36 |
def setup_logging(self):
|
| 37 |
logging.basicConfig(
|
|
|
|
| 42 |
|
| 43 |
async def initialize(self):
|
| 44 |
try:
|
| 45 |
+
from transformers import AutoTokenizer, AutoModel
|
| 46 |
self.tokenizer = AutoTokenizer.from_pretrained(
|
| 47 |
+
self.model_name,
|
| 48 |
trust_remote_code=True
|
| 49 |
)
|
| 50 |
self.model = AutoModel.from_pretrained(
|
| 51 |
+
self.model_name,
|
| 52 |
+
trust_remote_code=True,
|
| 53 |
+
torch_dtype=torch.float32 # CPU使用float32
|
| 54 |
).to(self.device)
|
| 55 |
+
|
| 56 |
self.model.eval()
|
| 57 |
+
torch.set_grad_enabled(False)
|
| 58 |
+
self.logger.info(f"模型加载成功,CPU线程数: {self.num_threads}")
|
| 59 |
except Exception as e:
|
| 60 |
self.logger.error(f"模型初始化失败: {str(e)}")
|
| 61 |
raise
|
| 62 |
|
| 63 |
@lru_cache(maxsize=1000)
|
| 64 |
+
async def generate_embedding(self, text: str) -> List[float]:
|
| 65 |
try:
|
| 66 |
inputs = self.tokenizer(
|
| 67 |
text,
|
| 68 |
return_tensors="pt",
|
| 69 |
truncation=True,
|
| 70 |
+
max_length=self.max_length,
|
| 71 |
+
padding=True
|
| 72 |
+
)
|
| 73 |
|
| 74 |
with torch.no_grad():
|
| 75 |
outputs = self.model(**inputs).last_hidden_state.mean(dim=1)
|
| 76 |
+
return outputs.numpy().tolist()[0]
|
| 77 |
except Exception as e:
|
| 78 |
self.logger.error(f"生成嵌入向量失败: {str(e)}")
|
| 79 |
raise
|
| 80 |
|
| 81 |
+
# FastAPI应用初始化
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 82 |
app = FastAPI(
|
| 83 |
title="Jina Embeddings API",
|
| 84 |
description="Text embedding generation service using jina-embeddings-v3",
|
| 85 |
version="1.0.0"
|
| 86 |
)
|
| 87 |
|
| 88 |
+
# 初始化服务
|
| 89 |
+
embedding_service = EmbeddingService()
|
| 90 |
+
|
| 91 |
+
# CORS配置
|
| 92 |
app.add_middleware(
|
| 93 |
CORSMiddleware,
|
| 94 |
allow_origins=["*"],
|
|
|
|
| 97 |
allow_headers=["*"],
|
| 98 |
)
|
| 99 |
|
| 100 |
+
# API端点
|
| 101 |
@app.post("/generate_embeddings", response_model=EmbeddingResponse)
|
| 102 |
@app.post("/api/v1/embeddings", response_model=EmbeddingResponse)
|
| 103 |
@app.post("/hf/v1/embeddings", response_model=EmbeddingResponse)
|
|
|
|
| 105 |
@app.post("/hf/v1/chat/completions", response_model=EmbeddingResponse)
|
| 106 |
async def generate_embeddings(request: EmbeddingRequest):
|
| 107 |
try:
|
| 108 |
+
embedding = await embedding_service.generate_embedding(request.input)
|
| 109 |
return EmbeddingResponse(
|
| 110 |
status="success",
|
| 111 |
+
embeddings=[embedding]
|
| 112 |
)
|
|
|
|
|
|
|
| 113 |
except Exception as e:
|
| 114 |
raise HTTPException(status_code=500, detail=str(e))
|
| 115 |
|
|
|
|
| 117 |
async def root():
|
| 118 |
return {
|
| 119 |
"status": "active",
|
| 120 |
+
"model": embedding_service.model_name,
|
| 121 |
+
"device": str(embedding_service.device),
|
| 122 |
+
"cpu_threads": embedding_service.num_threads
|
| 123 |
}
|
| 124 |
|
| 125 |
# Gradio界面
|
| 126 |
def gradio_interface(text: str) -> Dict:
|
| 127 |
try:
|
| 128 |
+
embedding = asyncio.run(embedding_service.generate_embedding(text))
|
| 129 |
return {
|
| 130 |
"status": "success",
|
| 131 |
+
"embeddings": [embedding]
|
| 132 |
}
|
| 133 |
except Exception as e:
|
| 134 |
return {
|
|
|
|
| 142 |
outputs=gr.JSON(label="嵌入向量结果"),
|
| 143 |
title="Jina Embeddings V3",
|
| 144 |
description="使用jina-embeddings-v3模型生成文本嵌入向量",
|
| 145 |
+
examples=[["这是一个测试句子。"]]
|
|
|
|
|
|
|
|
|
|
| 146 |
)
|
| 147 |
|
| 148 |
@app.on_event("startup")
|
|
|
|
| 150 |
await embedding_service.initialize()
|
| 151 |
|
| 152 |
if __name__ == "__main__":
|
| 153 |
+
# 初始化服务
|
| 154 |
asyncio.run(embedding_service.initialize())
|
| 155 |
|
| 156 |
+
# 挂载Gradio应用
|
| 157 |
gr.mount_gradio_app(app, iface, path="/ui")
|
| 158 |
|
| 159 |
+
# 启动服务
|
| 160 |
uvicorn.run(
|
| 161 |
app,
|
| 162 |
+
host="0.0.0.0",
|
| 163 |
+
port=7860,
|
| 164 |
+
workers=1,
|
| 165 |
+
loop="asyncio"
|
| 166 |
)
|