Views
No views yet
1from sentence_transformers import SentenceTransformer
2import torch
3import torch.nn.functional as F
4
5model = SentenceTransformer("truro7/vn-law-embedding", truncate_dim = 128)
6
7query = "Trộm cắp sẽ bị xử lý như thế nào?"
8
9corpus = """
10
11[100_2015_QH13]
12
13LUẬT HÌNH SỰ
14Điều 173. Tội trộm cắp tài sản
15
16Khoản 1:
17
181. Người nào trộm cắp tài sản của người khác trị giá từ 2.000.000 đồng đến dưới 50.000.000 đồng hoặc dưới 2.000.000 đồng nhưng thuộc một trong các trường hợp sau đây, thì bị phạt cải tạo không giam giữ đến 03 năm hoặc phạt tù từ 06 tháng đến 03 năm:
19a) Đã bị xử phạt vi phạm hành chính về hành vi chiếm đoạt tài sản mà còn vi phạm;
20b) Đã bị kết án về tội này hoặc về một trong các tội quy định tại các điều 168, 169, 170, 171, 172, 174, 175 và 290 của Bộ luật này, chưa được xóa án tích mà còn vi phạm;
21c) Gây ảnh hưởng xấu đến an ninh, trật tự, an toàn xã hội;
22d) Tài sản là phương tiện kiếm sống chính của người bị hại và gia đình họ; tài sản là kỷ vật, di vật, đồ thờ cúng có giá trị đặc biệt về mặt tinh thần đối với người bị hại.
23
24"""
25
26embedding = torch.tensor([model.encode(query)])
27corpus_embeddings = torch.tensor([model.encode(corpus)])
28
29cosine_similarities = F.cosine_similarity(embedding, corpus_embeddings)
30
31print(cosine_similarities.item()) #0.81
32
33
341from sentence_transformers import SentenceTransformer
2import torch
3import torch.nn.functional as F
4
5model = SentenceTransformer("truro7/vn-law-embedding", truncate_dim = 128)
6
7all_docs = read_all_docs() # Read all legal documents -> list of document contents
8top_k = 3
9embedding_docs = torch.load(vectordb_path, weights_only=False).to(self.device) # Vector database
10
11query = "Trộm cắp sẽ bị xử lý như thế nào?"
12embedding = torch.tensor(model.encode(query))
13
14cosine_similarities = F.cosine_similarity(embedding.unsqueeze(0).expand(self.embedding_docs.shape[0], 1, 128), self.embedding_docs, dim = -1).view(-1)
15top_k = cosine_similarities.topk(k)
16
17top_k_indices = top_k.indices
18top_k_values = top_k.values
19
20print(top_k_values) #Similarity scores
21
22for i in top_k_indices: #Show top k relevant documents
23 print(all_docs[i])
24 print("___________________________________________")
25