ppbrown commited on
Commit
fc81a95
1 Parent(s): 252da2a

Upload graph-byclip.py

Browse files
Files changed (1) hide show
  1. graph-byclip.py +77 -0
graph-byclip.py ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/env python
2
+
3
+ """ Work in progress
4
+ Plan:
5
+ Modded version of graph-embeddings.py
6
+ Just to see if using different CLIP module changes values significantly
7
+ (It does not)
8
+ This requires
9
+ pip install git+https://github.com/openai/CLIP.git
10
+ """
11
+
12
+
13
+ import sys
14
+ import json
15
+ import torch
16
+ import clip
17
+
18
+ import PyQt5
19
+ import matplotlib
20
+ matplotlib.use('QT5Agg') # Set the backend to TkAgg
21
+
22
+ import matplotlib.pyplot as plt
23
+
24
+ CLIPname= "ViT-L/14"
25
+
26
+ device=torch.device("cuda")
27
+ print("loading CLIP model")
28
+ model, processor = clip.load(CLIPname,device=device)
29
+ model.cuda().eval()
30
+ print("done")
31
+
32
+ def embed_from_text(text):
33
+ tokens = clip.tokenize(text).to(device)
34
+
35
+ with torch.no_grad():
36
+ embed = model.encode_text(tokens)
37
+ return embed
38
+
39
+
40
+ # Expect SINGLE WORD ONLY
41
+ def standard_embed_calc(text):
42
+ inputs = processor(text=text, return_tensors="pt")
43
+ inputs.to(device)
44
+ with torch.no_grad():
45
+ text_features = model.get_text_features(**inputs)
46
+ embedding = text_features[0]
47
+ return embedding
48
+
49
+
50
+ fig, ax = plt.subplots()
51
+
52
+
53
+ text1 = input("First word or prompt: ")
54
+ text2 = input("Second prompt(or leave blank): ")
55
+
56
+
57
+ print("generating embeddings for each now")
58
+ emb1 = embed_from_text(text1)
59
+ print("shape of emb1:",emb1.shape)
60
+
61
+ graph1=emb1[0].tolist()
62
+ ax.plot(graph1, label=text1[:20])
63
+
64
+ if len(text2) >0:
65
+ emb2 = embed_from_text(text2)
66
+ graph2=emb2[0].tolist()
67
+ ax.plot(graph2, label=text2[:20])
68
+
69
+ # Add labels, title, and legend
70
+ #ax.set_xlabel('Index')
71
+ ax.set_ylabel('Values')
72
+ ax.set_title('Comparative Graph of Two Embeddings')
73
+ ax.legend()
74
+
75
+ # Display the graph
76
+ print("Pulling up the graph")
77
+ plt.show()