Spaces:
Running
Running
create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,108 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import numpy as np
|
3 |
+
from transformers import AutoModel, AutoTokenizer
|
4 |
+
|
5 |
+
# load model and tokenizer
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True)
|
7 |
+
model = AutoModel.from_pretrained('jinaai/jina-embeddings-v2-base-zh', trust_remote_code=True)
|
8 |
+
|
9 |
+
|
10 |
+
def chunk_by_sentences(input_text: str, tokenizer: callable, separator: str):
|
11 |
+
inputs = tokenizer(input_text, return_tensors='pt', return_offsets_mapping=True)
|
12 |
+
punctuation_mark_id = tokenizer.convert_tokens_to_ids(separator)
|
13 |
+
print(f"separator: {separator}, punctuation_mark_id: {punctuation_mark_id}")
|
14 |
+
sep_id = tokenizer.eos_token_id
|
15 |
+
token_offsets = inputs['offset_mapping'][0]
|
16 |
+
token_ids = inputs['input_ids'][0]
|
17 |
+
chunk_positions = [
|
18 |
+
(i, int(start + 1))
|
19 |
+
for i, (token_id, (start, end)) in enumerate(zip(token_ids, token_offsets))
|
20 |
+
if token_id == punctuation_mark_id
|
21 |
+
and (
|
22 |
+
token_offsets[i + 1][0] - token_offsets[i][1] >= 0
|
23 |
+
or token_ids[i + 1] == sep_id
|
24 |
+
)
|
25 |
+
]
|
26 |
+
chunks = [
|
27 |
+
input_text[x[1]: y[1]]
|
28 |
+
for x, y in zip([(1, 0)] + chunk_positions[:-1], chunk_positions)
|
29 |
+
]
|
30 |
+
span_annotations = [
|
31 |
+
(x[0], y[0]) for (x, y) in zip([(1, 0)] + chunk_positions[:-1], chunk_positions)
|
32 |
+
]
|
33 |
+
return chunks, span_annotations
|
34 |
+
|
35 |
+
|
36 |
+
def late_chunking(model_output, span_annotation, max_length=None):
|
37 |
+
token_embeddings = model_output[0]
|
38 |
+
outputs = []
|
39 |
+
for embeddings, annotations in zip(token_embeddings, span_annotation):
|
40 |
+
if max_length is not None:
|
41 |
+
annotations = [
|
42 |
+
(start, min(end, max_length - 1))
|
43 |
+
for (start, end) in annotations
|
44 |
+
if start < (max_length - 1)
|
45 |
+
]
|
46 |
+
pooled_embeddings = [
|
47 |
+
embeddings[start:end].sum(dim=0) / (end - start)
|
48 |
+
for start, end in annotations
|
49 |
+
if (end - start) >= 1
|
50 |
+
]
|
51 |
+
pooled_embeddings = [
|
52 |
+
embedding.detach().cpu().numpy() for embedding in pooled_embeddings
|
53 |
+
]
|
54 |
+
outputs.append(pooled_embeddings)
|
55 |
+
|
56 |
+
return outputs
|
57 |
+
|
58 |
+
|
59 |
+
def embedding_retriever(query_input, text_input, separator):
|
60 |
+
chunks, span_annotations = chunk_by_sentences(text_input, tokenizer, separator)
|
61 |
+
print(f"chunks: ", chunks)
|
62 |
+
inputs = tokenizer(text_input, return_tensors='pt', max_length=4096, truncation=True)
|
63 |
+
model_output = model(**inputs)
|
64 |
+
late_chunking_embeddings = late_chunking(model_output, [span_annotations])[0]
|
65 |
+
|
66 |
+
query_inputs = tokenizer(query_input, return_tensors='pt')
|
67 |
+
query_embedding = model(**query_inputs)[0].detach().cpu().numpy().mean(axis=1)
|
68 |
+
|
69 |
+
traditional_chunking_embeddings = model.encode(chunks)
|
70 |
+
|
71 |
+
cos_sim = lambda x, y: np.dot(x, y) / (np.linalg.norm(x) * np.linalg.norm(y))
|
72 |
+
|
73 |
+
naive_embedding_score_dict = {}
|
74 |
+
late_chunking_embedding_score_dict = {}
|
75 |
+
for chunk, trad_embed, new_embed in zip(chunks, traditional_chunking_embeddings, late_chunking_embeddings):
|
76 |
+
# 计算query和每个chunk的embedding的cosine similarity,相似度分数转化为float类型
|
77 |
+
naive_embedding_score_dict[chunk] = round(cos_sim(query_embedding, trad_embed).tolist()[0], 4)
|
78 |
+
late_chunking_embedding_score_dict[chunk] = round(cos_sim(query_embedding, new_embed).tolist()[0], 4)
|
79 |
+
|
80 |
+
naive_embedding_order = sorted(
|
81 |
+
naive_embedding_score_dict.items(), key=lambda x: x[1], reverse=True
|
82 |
+
)
|
83 |
+
late_chunking_order = sorted(
|
84 |
+
late_chunking_embedding_score_dict.items(), key=lambda x: x[1], reverse=True
|
85 |
+
)
|
86 |
+
|
87 |
+
df_data = []
|
88 |
+
for i in range(len(naive_embedding_order)):
|
89 |
+
df_data.append([i+1, naive_embedding_order[i][0], naive_embedding_order[i][1],
|
90 |
+
late_chunking_order[i][0], late_chunking_order[i][1]])
|
91 |
+
return df_data
|
92 |
+
|
93 |
+
|
94 |
+
if __name__ == '__main__':
|
95 |
+
with gr.Blocks() as demo:
|
96 |
+
query = gr.TextArea(lines=1, placeholder="your query", label="Query")
|
97 |
+
text = gr.TextArea(lines=3, placeholder="your text", label="Text")
|
98 |
+
sep = gr.TextArea(lines=1, placeholder="your separator", label="Separator")
|
99 |
+
submit = gr.Button("Submit")
|
100 |
+
result = gr.DataFrame(headers=["order", "naive_embedding_text", "naive_embedding_score",
|
101 |
+
"late_chunking_text", "late_chunking_score"],
|
102 |
+
label="Retrieve Result",
|
103 |
+
wrap=True)
|
104 |
+
|
105 |
+
submit.click(fn=embedding_retriever,
|
106 |
+
inputs=[query, text, sep],
|
107 |
+
outputs=[result])
|
108 |
+
demo.launch()
|