ning8429 commited on
Commit
2184c4e
·
verified ·
1 Parent(s): 558a77a

Upload clip.py

Browse files
Files changed (1) hide show
  1. clip.py +70 -0
clip.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import torch
3
+ from PIL import Image
4
+ from transformers import ChineseCLIPProcessor, ChineseCLIPModel
5
+
6
+ def clip_result(image_path):
7
+ # 設置設備
8
+ device = "cuda" if torch.cuda.is_available() else "cpu"
9
+
10
+ # Get the directory where this script is located
11
+ script_dir = os.path.dirname(os.path.abspath(__file__))
12
+
13
+ # Construct the full path to the file in the subfolder
14
+ model_path = os.path.join(script_dir, 'model', 'best_clip_model.pth')
15
+
16
+ # 載入訓練好的模型和處理器
17
+ model = ChineseCLIPModel.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
18
+ model.load_state_dict(torch.load(model_path, map_location=device))
19
+ model = model.to(device)
20
+ model.eval()
21
+
22
+ processor = ChineseCLIPProcessor.from_pretrained("OFA-Sys/chinese-clip-vit-base-patch16")
23
+
24
+ # 1. 加載圖片
25
+ # image_path = '/content/drive/MyDrive/幽靈吉伊卡哇.png'
26
+ image = Image.open(image_path)
27
+
28
+ # 2. 加載中文詞彙表
29
+ with open('/content/drive/MyDrive/chiikawa/word_list.txt', 'r', encoding='utf-8') as f:
30
+ vocab = [line.strip() for line in f.readlines()]
31
+
32
+ # 3. 圖像和文本處理
33
+ batch_size = 16 # 每次處理16個詞彙
34
+ similarities = []
35
+
36
+ # 釋放未使用的顯存
37
+ torch.cuda.empty_cache()
38
+
39
+ with torch.no_grad():
40
+ for i in range(0, len(vocab), batch_size):
41
+ batch_vocab = vocab[i:i + batch_size]
42
+ inputs = processor(
43
+ text=batch_vocab,
44
+ images=image,
45
+ return_tensors="pt",
46
+ padding=True
47
+ ).to(device)
48
+
49
+ # 推理並進行相似度計算
50
+ outputs = model(**inputs)
51
+ image_embeds = outputs.image_embeds / outputs.image_embeds.norm(dim=-1, keepdim=True)
52
+ text_embeds = outputs.text_embeds / outputs.text_embeds.norm(dim=-1, keepdim=True)
53
+ similarity = torch.matmul(image_embeds, text_embeds.T).squeeze(0)
54
+ similarities.append(similarity)
55
+
56
+ # 4. 合併所有相似度
57
+ similarity = torch.cat(similarities, dim=0)
58
+
59
+ # 5. 找到相似度最高的詞彙
60
+ top_k = 3
61
+ top_k_indices = torch.topk(similarity, top_k).indices.tolist()
62
+ top_k_words = [vocab[idx] for idx in top_k_indices]
63
+
64
+ # 6. 輸出最接近的前3名中文詞彙
65
+
66
+ print("最接近的前3名中文詞彙是:")
67
+ for rank, word in enumerate(top_k_words, 1):
68
+ print(f"{rank}. {word}")
69
+
70
+ return top_k_words