ChristophSchuhmann commited on
Commit
f9b152c
1 Parent(s): 12a1515

Upload 4 files

Browse files
Files changed (5) hide show
  1. .gitattributes +1 -0
  2. emo-image-links (1).csv +3 -0
  3. mean_sims.npy +3 -0
  4. std_dev_sims.npy +3 -0
  5. zero.py +174 -0
.gitattributes CHANGED
@@ -53,3 +53,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
53
  *.jpg filter=lfs diff=lfs merge=lfs -text
54
  *.jpeg filter=lfs diff=lfs merge=lfs -text
55
  *.webp filter=lfs diff=lfs merge=lfs -text
 
 
53
  *.jpg filter=lfs diff=lfs merge=lfs -text
54
  *.jpeg filter=lfs diff=lfs merge=lfs -text
55
  *.webp filter=lfs diff=lfs merge=lfs -text
56
+ emo-image-links[[:space:]](1).csv filter=lfs diff=lfs merge=lfs -text
emo-image-links (1).csv ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b801337488fe1aa001878cf27c08c6567fe928a58a33360343706166779ccba8
3
+ size 23988668
mean_sims.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b77dde5d3c4d20aae5d2dc5b04377366bcf2ae9f492ee50754757c0c6f38cf98
3
+ size 1456
std_dev_sims.npy ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:2f7bda8e3efef7f6b2ca077e95739385d26b46550b59893f7a0a5213812cd825
3
+ size 1456
zero.py ADDED
@@ -0,0 +1,174 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ emotions = [
2
+ 'tart', 'acidic', 'bitter', 'tangy', 'vinegary', 'sharp',
3
+ 'thankful', 'appreciative', 'obliged', 'indebted', 'gratified', 'recognizant',
4
+ 'dignified', 'haughty', 'arrogant', 'self-satisfied', 'vain', 'honored',
5
+ 'repulsed', 'appalled', 'revolted', 'nauseated', 'repelled', 'sickened', 'ebullient', 'merry', 'jovial', 'cheerful', 'lighthearted', 'joyful', 'beaming', 'grinning', 'elated', 'gleeful', 'happy', 'hopeful', 'gratitude', 'thankful', 'buoyant', 'upbeat', 'vibrant', 'radiant', 'exuberant', 'zestful', 'chirpy', 'peppy', 'jaunty', 'sprightly', 'brisk', 'lively', 'animated', 'energized', 'revitalized', 'invigorated', 'activated', 'energetic', 'dynamic', 'electrified', 'bouncy', 'effervescent', 'chipper', 'jubilant',
6
+ 'mindful', 'unruffled', 'coolheaded', 'level headed', 'poised', 'self-possessed', 'unflappable', 'collected', 'unperturbed', 'untroubled', 'unrattled', 'unshaken', 'unflustered', 'composed', 'relaxed', 'tranquil', 'serene', 'calm', 'centered', 'peaceful', 'imperturbable', 'reposeful', 'grounded', 'equanimous', 'harmonious',
7
+ 'engaging', 'focused', 'watchful', 'attentive', 'heedful', 'scrutinizing', 'investigating', 'alert', 'studious', 'analyzing', 'examining', 'cognizant', 'inquiring', 'questioning', 'probing', 'introspecting', 'introspective', 'observant',
8
+ 'wondering', 'awe', 'intrigued', 'spellbinding', 'fascinated', 'mesmerized', 'captivated', 'bewitching', 'beguiling', 'agog', 'marveling', 'gazing', 'mystified', 'curious', 'riveted', 'enrapturing', 'entrancing', 'hypnotic', 'mesmerizing', 'alluring', 'enthralled',
9
+ 'pensive', 'ruminative', 'brooding', 'contemplating', 'meditative', 'reflective', 'pondering', 'cogitating', 'speculative',
10
+ 'trembling', 'shuddery', 'afraid', 'spooked', 'apprehensive', 'fearful', 'terrorized', 'petrified', 'scared', 'horror-struck', 'quavering', 'shuddering', 'frightened', 'trepid', 'distraught', 'alarmed', 'fear-stricken', 'quaking', 'anxious', 'nervous', 'uneasy', 'worried', 'tense', 'jittery', 'jumpy', 'startled', 'edgy', 'antsy', 'rattled', 'distracted', 'disquieted', 'skittish', 'restless', 'restive', 'panic-stricken', 'panicked',
11
+ 'dumbstruck', 'bewildered', 'dumbfounded', 'stunned', 'stupefied', 'thunderstruck', 'staggered', 'amazed', 'astonished', 'astounded', 'surprised', 'shocked', 'flabbergasted', 'befuddled', 'perplexed', 'puzzled', 'confounded', 'baffled', 'discombobulated', 'flummoxed',
12
+ 'sad', 'dismal', 'forlorn', 'depressed', 'woebegone', 'plaintive', 'sorrowful', 'gloomy', 'lugubrious', 'melancholic', 'blue', 'desolate', 'miserable', 'downhearted', 'morose', 'somber', 'despairing', 'woeful', 'heartbroken', 'crestfallen', 'dispirited',
13
+ 'romantic', 'amorous', 'passionate', 'sensual', 'erotic', 'sultry', 'salacious', 'libidinous', 'sensuous', 'carnal', 'lustful', 'infatuated', 'desirous', 'lecherous', 'lust-driven', 'prurient', 'enflamed', 'voluptuous', 'sizzling', 'torrid', 'steaminess',
14
+ 'seductive', 'titillating', 'awakened', 'ravishing', 'enticing', 'charming', 'irresistible', 'provoked', 'craving', 'stimulated', 'aroused', 'magnetic', 'compelling', 'flirty', 'bellicose',
15
+ 'aggravated', 'perturbed', 'enraged', 'furious', 'irate', 'incensed', 'infuriated', 'wrathful', 'livid', 'cross', 'galled', 'resentful', 'bitter', 'indignant', 'outraged', 'exasperated', 'maddened', 'angry', 'annoyed', 'vexed', 'truculent', 'spiky', 'prickly', 'snarly', 'huffy', 'nettled', 'irritable', 'piqued', 'snappish', 'irascible', 'testy', 'nerved',
16
+ 'persistent', 'resilient', 'determined', 'unfailing', 'unyielding', 'tenacious', 'steadfast', 'adamant', 'resolute', 'undaunted', 'unwavering', 'unswerving', 'unflinching', 'unrelenting', 'enduring', 'indefatigable', 'motivated', 'driven',
17
+ 'discomposed', 'nonplussed', 'disconcerted', 'disturbed', 'ruffled', 'troubled', 'stressed', 'fractious', 'cringing', 'quailing', 'cowering', 'daunted', 'dread-filled', 'intimidated', 'unnerved', 'unsettled', 'fretful', 'ticked-off', 'flustered',
18
+ 'belligerent', 'pugnacious', 'contentious', 'quarrelsome', 'grumpy', 'grouchy', 'sulky', 'cranky', 'crabby', 'cantankerous', 'curmudgeonly', 'waspy', 'combative', 'argumentative', 'scrappy'
19
+ ]
20
+
21
+
22
+
23
+
24
+ import torch
25
+ import open_clip
26
+ import requests
27
+ from PIL import Image
28
+ from torchvision.transforms.functional import to_pil_image
29
+ import matplotlib.pyplot as plt
30
+ import seaborn as sns
31
+ import numpy as np
32
+ import requests
33
+ from PIL import Image
34
+ from IPython.display import display
35
+ from io import BytesIO
36
+
37
+
38
+ # Load the CLIP model and tokenizer
39
+ model_clip, preprocess_train, preprocess_val = open_clip.create_model_and_transforms('hf-hub:apple/DFN5B-CLIP-ViT-H-14-378')
40
+ tokenizer = open_clip.get_tokenizer('hf-hub:apple/DFN5B-CLIP-ViT-H-14-378')
41
+
42
+ # Function to download image from URL
43
+ def download_image(image_url):
44
+ response = requests.get(image_url, timeout=1)
45
+ response.raise_for_status()
46
+ return Image.open(requests.get(image_url, stream=True).raw)
47
+
48
+
49
+
50
+ # Diese Funktion konvertiert PyTorch-Tensoren in Numpy-Arrays und löscht die Tensoren
51
+ def tensor_to_array(tensor):
52
+ array = tensor.detach().cpu().numpy()
53
+ del tensor # Lösche den Tensor, um Speicher freizugeben
54
+ return array
55
+
56
+ # Softmax-Funktion für Numpy-Arrays
57
+ def softmax(x):
58
+ e_x = np.exp(x - np.max(x))
59
+ return e_x / e_x.sum(axis=-1, keepdims=True)
60
+
61
+
62
+
63
+
64
+ '''
65
+
66
+ # Tokenize the prompts
67
+ text = tokenizer(emotions)
68
+
69
+ with torch.no_grad():
70
+
71
+ text_features = model_clip.encode_text(text)
72
+
73
+ text_features /= text_features.norm(dim=-1, keepdim=True)
74
+ text_features = tensor_to_array(text_features)
75
+
76
+ # Save the NumPy array to a file
77
+ np.save('text_features.npy', text_features)
78
+ '''
79
+
80
+ # Later or elsewhere in your code, load the NumPy array from the file
81
+ text_features = np.load('text_features.npy')
82
+
83
+
84
+
85
+ def zeroshot_classifier(image_url):
86
+ # Download and preprocess the image
87
+
88
+ image = download_image(image_url)
89
+ image_preprocessed = preprocess_val(image).unsqueeze(0)
90
+ image_features = model_clip.encode_image(image_preprocessed)
91
+ image_features = tensor_to_array(image_features) # Konvertieren in Numpy-Array
92
+ image_features /= np.linalg.norm(image_features, axis=-1, keepdims=True)
93
+
94
+
95
+ # Load the mean_sims array from the file
96
+ loaded_mean_sims = np.load('mean_sims.npy')
97
+ #print("Loaded Mean Similarity Scores:", loaded_mean_sims)
98
+ loaded_stdev_sims = np.load('std_dev_sims.npy')
99
+ sims =np.matmul(image_features, text_features.T)
100
+ normalized_sims = (sims - loaded_mean_sims) / loaded_stdev_sims
101
+
102
+
103
+
104
+ # Hier sollten Sie auch die Textfeatures in Numpy-Arrays konvertieren, bevor Sie diese Funktion verwenden.
105
+ text_probs = softmax(100.0 * sims)
106
+ return text_probs, sims
107
+
108
+
109
+
110
+ def display_image_from_url(url, base_width=300):
111
+ try:
112
+ # Send a HTTP request to the URL
113
+ response = requests.get(url)
114
+ # Raise an exception if the request was unsuccessful
115
+ response.raise_for_status()
116
+
117
+ # Open the image from the bytes in the response content
118
+ img = Image.open(BytesIO(response.content))
119
+
120
+ # Calculate the new height to maintain the aspect ratio
121
+ w_percent = (base_width / float(img.size[0]))
122
+ h_size = int((float(img.size[1]) * float(w_percent)))
123
+
124
+ # Resize the image
125
+ img = img.resize((base_width, h_size), Image.ANTIALIAS)
126
+
127
+ # Display the image
128
+ #display(img)
129
+ except:
130
+ pass
131
+
132
+
133
+ import pandas as pd
134
+
135
+ # Read the CSV file
136
+ #df = pd.read_csv('emo-image-links (1).csv')
137
+
138
+ #urls = df["url"].tolist()[:1000]
139
+
140
+
141
+ urls=["https://i.imgur.com/lQCGbw9.png","https://i.imgur.com/saUX1yc.png", 'https://media.gettyimages.com/id/1027697458/de/foto/nostalgische-frau.jpg?s=1024x1024&w=gi&k=20&c=eJlr2c7K1_nFAfv0Sdt6sn4yhz6K_Y78rKbJMvoXlFs=', "https://i.imgur.com/BI3zkNG.jpg", "https://i.imgur.com/3WbnImZ.jpg","https://i.imgur.com/78IlUDZ.png","https://i.imgur.com/29FZiD9.jpg","https://i.imgur.com/2fun8N3.png","https://i.imgur.com/lGLpebl.jpg","https://imagizer.imageshack.com/img924/7428/HH6wua.png","https://i.imgur.com/F22ZjZw.jpg","https://i.imgur.com/HPJQCEp.jpg","https://i.imgur.com/XtSd4pO.png"]
142
+ simlist=[]
143
+ for url in urls:
144
+ #display_image_from_url(url)
145
+ print("##############")
146
+ print(url)
147
+ try:
148
+ probs, sims = zeroshot_classifier(url)
149
+ except:
150
+ continue
151
+ #print(sims)
152
+ simlist.append(sims)
153
+ for i in range (probs.shape[1]):
154
+ if probs[0][i]>0.05:
155
+ print(probs[0][i],emotions[i])
156
+
157
+ # Convert simlist to a NumPy array
158
+ simlist_array = np.array(simlist)
159
+
160
+ # Calculate the standard deviation
161
+ std_dev = np.std(simlist_array, axis=0)
162
+
163
+ print("Standard Deviation of similarity scores:", std_dev)
164
+
165
+ mean_sims = np.mean(np.array(simlist), axis=0)
166
+ #print("Mean similarity scores:", mean_sims)
167
+
168
+ # Save the mean_sims array to a file
169
+ #np.save('mean_sims.npy', mean_sims)
170
+
171
+ # Save the mean_sims array to a file
172
+ #np.save('std_dev_sims.npy', std_dev)
173
+
174
+