Spaces:
Sleeping
Sleeping
LINYINGHAO
commited on
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,32 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
from transformers import AutoTokenizer, AutoModel
|
3 |
+
import torch
|
4 |
+
|
5 |
+
# 1. 加载模型和分词器
|
6 |
+
model_name = "jinaai/jina-embeddings-v3" # 替换为您实际使用的模型名
|
7 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
|
8 |
+
model = AutoModel.from_pretrained(model_name, trust_remote_code=True)
|
9 |
+
|
10 |
+
# 2. 定义生成嵌入的函数
|
11 |
+
def generate_embeddings(text):
|
12 |
+
# 使用分词器处理输入文本
|
13 |
+
inputs = tokenizer(text, return_tensors="pt")
|
14 |
+
# 禁用梯度计算,以减少资源消耗
|
15 |
+
with torch.no_grad():
|
16 |
+
# 获取最后一层隐藏状态并计算平均值作为嵌入
|
17 |
+
embeddings = model(**inputs).last_hidden_state.mean(dim=1)
|
18 |
+
# 将嵌入转换为Python列表,方便Gradio输出
|
19 |
+
return embeddings.numpy().tolist()
|
20 |
+
|
21 |
+
# 3. 使用Gradio定义接口
|
22 |
+
iface = gr.Interface(
|
23 |
+
fn=generate_embeddings, # 调用嵌入生成函数
|
24 |
+
inputs="text", # 输入类型为文本
|
25 |
+
outputs="json", # 输出为JSON格式,方便API调用
|
26 |
+
title="Text Embedding Generator",
|
27 |
+
description="Enter text to generate embeddings using the Jina model."
|
28 |
+
)
|
29 |
+
|
30 |
+
# 4. 启动Gradio应用
|
31 |
+
if __name__ == "__main__":
|
32 |
+
iface.launch()
|