Spaces:
Runtime error
Runtime error
sickcell69
commited on
Update app.py
Browse files
app.py
CHANGED
@@ -1,39 +1,66 @@
|
|
1 |
-
import
|
2 |
-
import
|
3 |
-
from sentence_transformers import SentenceTransformer, util
|
4 |
import torch
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
|
7 |
-
|
8 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
9 |
|
10 |
-
#
|
11 |
-
|
12 |
-
|
|
|
13 |
|
14 |
-
#
|
15 |
-
|
16 |
-
corpus_embeddings = torch.load(embeddings_path, map_location=torch.device('cpu'))
|
17 |
|
18 |
-
|
19 |
-
|
20 |
-
|
21 |
-
|
|
|
|
|
|
|
|
|
22 |
results = []
|
23 |
-
for
|
24 |
-
|
25 |
-
|
26 |
-
|
27 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
28 |
|
|
|
29 |
iface = gr.Interface(
|
30 |
-
fn=
|
31 |
-
inputs="
|
32 |
-
outputs=
|
33 |
-
title="
|
34 |
-
description="
|
35 |
)
|
36 |
|
37 |
-
|
38 |
-
|
39 |
-
iface.launch(share=True) #網頁跑不出來
|
|
|
1 |
+
import json
|
2 |
+
import os
|
|
|
3 |
import torch
|
4 |
+
from sentence_transformers import SentenceTransformer
|
5 |
+
import faiss
|
6 |
+
import numpy as np
|
7 |
+
import gradio as gr
|
8 |
|
9 |
+
def load_or_create_model_and_embeddings(model_name, data_file):
|
10 |
+
model_path = os.path.join(output_dir, 'saved_model')
|
11 |
+
embeddings_path = os.path.join(output_dir, 'corpus_embeddings.pt')
|
12 |
+
if os.path.exists(model_path) and os.path.exists(embeddings_path):
|
13 |
+
print("載入已保存的模型和嵌入...")
|
14 |
+
model = SentenceTransformer(model_path)
|
15 |
+
embeddings = torch.load(embeddings_path)
|
16 |
+
else:
|
17 |
+
model = SentenceTransformer(model_name)
|
18 |
+
with open(data_file, 'r', encoding='utf-8') as f:
|
19 |
+
data = json.load(f)
|
20 |
+
texts = [item['text'] for item in data]
|
21 |
+
embeddings = model.encode(texts, convert_to_tensor=True)
|
22 |
+
return model, embeddings
|
23 |
|
24 |
+
# 設置參數
|
25 |
+
model_name = 'sentence-transformers/all-MiniLM-L6-v2'
|
26 |
+
data_file = 'labeled_cti_data.json'
|
27 |
+
output_dir = '.'
|
28 |
|
29 |
+
# 載入或創建模型和嵌入
|
30 |
+
model, embeddings= load_or_create_model_and_embeddings(model_name, data_file)
|
|
|
31 |
|
32 |
+
# 創建 Faiss 索引
|
33 |
+
dimension = embeddings.shape[1]
|
34 |
+
index = faiss.IndexFlatL2(dimension)
|
35 |
+
index.add(embeddings.cpu().numpy().astype('float32'))
|
36 |
+
|
37 |
+
def semantic_search(query, top_k=3):
|
38 |
+
query_vector = model.encode([query], convert_to_tensor=True)
|
39 |
+
distances, indices = index.search(query_vector.cpu().numpy().astype('float32'), top_k)
|
40 |
results = []
|
41 |
+
for i, idx in enumerate(indices[0]):
|
42 |
+
results.append({
|
43 |
+
'text': texts[idx],
|
44 |
+
'similarity_score': 1 - distances[0][i] / 2
|
45 |
+
})
|
46 |
+
return results
|
47 |
+
|
48 |
+
def search_and_format(query):
|
49 |
+
results = semantic_search(query)
|
50 |
+
formatted_results = ""
|
51 |
+
for i, result in enumerate(results, 1):
|
52 |
+
formatted_results += f"{i}. 相似度分數: {result['similarity_score']:.4f}\n"
|
53 |
+
formatted_results += f" 情一: {result['text']}\n\n"
|
54 |
+
return formatted_results
|
55 |
|
56 |
+
# 創建Gradio界面
|
57 |
iface = gr.Interface(
|
58 |
+
fn=search_and_format,
|
59 |
+
inputs=gr.Textbox(lines=2, placeholder="輸入您的搜索查詢..."),
|
60 |
+
outputs=gr.Textbox(lines=10),
|
61 |
+
title="語義搜索",
|
62 |
+
description="輸入查詢以搜索相關文本。將顯示前3個最相關的結果。"
|
63 |
)
|
64 |
|
65 |
+
# 啟動Gradio界面
|
66 |
+
iface.launch()
|
|