File size: 8,751 Bytes
f9b152c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
emotions = [
    'tart', 'acidic', 'bitter', 'tangy', 'vinegary', 'sharp',
    'thankful', 'appreciative', 'obliged', 'indebted', 'gratified', 'recognizant',
    'dignified', 'haughty', 'arrogant', 'self-satisfied', 'vain', 'honored',
    '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',
'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',
'engaging', 'focused', 'watchful', 'attentive', 'heedful', 'scrutinizing', 'investigating', 'alert', 'studious', 'analyzing', 'examining', 'cognizant', 'inquiring', 'questioning', 'probing', 'introspecting', 'introspective', 'observant',
'wondering', 'awe', 'intrigued', 'spellbinding', 'fascinated', 'mesmerized', 'captivated', 'bewitching', 'beguiling', 'agog', 'marveling', 'gazing', 'mystified', 'curious', 'riveted', 'enrapturing', 'entrancing', 'hypnotic', 'mesmerizing', 'alluring', 'enthralled',
'pensive', 'ruminative', 'brooding', 'contemplating', 'meditative', 'reflective', 'pondering', 'cogitating', 'speculative',
'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',
'dumbstruck', 'bewildered', 'dumbfounded', 'stunned', 'stupefied', 'thunderstruck', 'staggered', 'amazed', 'astonished', 'astounded', 'surprised', 'shocked', 'flabbergasted', 'befuddled', 'perplexed', 'puzzled', 'confounded', 'baffled', 'discombobulated', 'flummoxed',
'sad', 'dismal', 'forlorn', 'depressed', 'woebegone', 'plaintive', 'sorrowful', 'gloomy', 'lugubrious', 'melancholic', 'blue', 'desolate', 'miserable', 'downhearted', 'morose', 'somber', 'despairing', 'woeful', 'heartbroken', 'crestfallen', 'dispirited',
'romantic', 'amorous', 'passionate', 'sensual', 'erotic', 'sultry', 'salacious', 'libidinous', 'sensuous', 'carnal', 'lustful', 'infatuated', 'desirous', 'lecherous', 'lust-driven', 'prurient', 'enflamed', 'voluptuous', 'sizzling', 'torrid', 'steaminess',
'seductive', 'titillating', 'awakened', 'ravishing', 'enticing', 'charming', 'irresistible', 'provoked', 'craving', 'stimulated', 'aroused', 'magnetic', 'compelling', 'flirty', 'bellicose',
'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',
'persistent', 'resilient', 'determined', 'unfailing', 'unyielding', 'tenacious', 'steadfast', 'adamant', 'resolute', 'undaunted', 'unwavering', 'unswerving', 'unflinching', 'unrelenting', 'enduring', 'indefatigable', 'motivated', 'driven',
'discomposed', 'nonplussed', 'disconcerted', 'disturbed', 'ruffled', 'troubled', 'stressed', 'fractious', 'cringing', 'quailing', 'cowering', 'daunted', 'dread-filled', 'intimidated', 'unnerved', 'unsettled', 'fretful', 'ticked-off', 'flustered',
'belligerent', 'pugnacious', 'contentious', 'quarrelsome', 'grumpy', 'grouchy', 'sulky', 'cranky', 'crabby', 'cantankerous', 'curmudgeonly', 'waspy', 'combative', 'argumentative', 'scrappy'
]




import torch
import open_clip
import requests
from PIL import Image
from torchvision.transforms.functional import to_pil_image
import matplotlib.pyplot as plt
import seaborn as sns
import numpy as np
import requests
from PIL import Image
from IPython.display import display
from io import BytesIO


# Load the CLIP model and tokenizer
model_clip, preprocess_train, preprocess_val = open_clip.create_model_and_transforms('hf-hub:apple/DFN5B-CLIP-ViT-H-14-378')
tokenizer = open_clip.get_tokenizer('hf-hub:apple/DFN5B-CLIP-ViT-H-14-378')

# Function to download image from URL
def download_image(image_url):
    response = requests.get(image_url, timeout=1)
    response.raise_for_status()
    return Image.open(requests.get(image_url, stream=True).raw)



# Diese Funktion konvertiert PyTorch-Tensoren in Numpy-Arrays und löscht die Tensoren
def tensor_to_array(tensor):
    array = tensor.detach().cpu().numpy()
    del tensor  # Lösche den Tensor, um Speicher freizugeben
    return array

# Softmax-Funktion für Numpy-Arrays
def softmax(x):
    e_x = np.exp(x - np.max(x))
    return e_x / e_x.sum(axis=-1, keepdims=True)




'''

# Tokenize the prompts
text = tokenizer(emotions)

with torch.no_grad():

    text_features = model_clip.encode_text(text)

    text_features /= text_features.norm(dim=-1, keepdim=True)
text_features = tensor_to_array(text_features)

# Save the NumPy array to a file
np.save('text_features.npy', text_features)
'''

# Later or elsewhere in your code, load the NumPy array from the file
text_features = np.load('text_features.npy')



def zeroshot_classifier(image_url):
    # Download and preprocess the image

    image = download_image(image_url)
    image_preprocessed = preprocess_val(image).unsqueeze(0)
    image_features = model_clip.encode_image(image_preprocessed)
    image_features = tensor_to_array(image_features)  # Konvertieren in Numpy-Array
    image_features /= np.linalg.norm(image_features, axis=-1, keepdims=True)


    # Load the mean_sims array from the file
    loaded_mean_sims = np.load('mean_sims.npy')
    #print("Loaded Mean Similarity Scores:", loaded_mean_sims)
    loaded_stdev_sims = np.load('std_dev_sims.npy')
    sims =np.matmul(image_features, text_features.T)
    normalized_sims = (sims - loaded_mean_sims) / loaded_stdev_sims



    # Hier sollten Sie auch die Textfeatures in Numpy-Arrays konvertieren, bevor Sie diese Funktion verwenden.
    text_probs = softmax(100.0 * sims)
    return text_probs, sims



def display_image_from_url(url, base_width=300):
  try:
    # Send a HTTP request to the URL
    response = requests.get(url)
    # Raise an exception if the request was unsuccessful
    response.raise_for_status()

    # Open the image from the bytes in the response content
    img = Image.open(BytesIO(response.content))

    # Calculate the new height to maintain the aspect ratio
    w_percent = (base_width / float(img.size[0]))
    h_size = int((float(img.size[1]) * float(w_percent)))

    # Resize the image
    img = img.resize((base_width, h_size), Image.ANTIALIAS)

    # Display the image
    #display(img)
  except:
    pass


import pandas as pd

# Read the CSV file
#df = pd.read_csv('emo-image-links (1).csv')

#urls = df["url"].tolist()[:1000]


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"]
simlist=[]
for url in urls:
  #display_image_from_url(url)
  print("##############")
  print(url)
  try:
    probs, sims = zeroshot_classifier(url)
  except:
     continue
  #print(sims)
  simlist.append(sims)
  for i in range (probs.shape[1]):
    if probs[0][i]>0.05:
      print(probs[0][i],emotions[i])

# Convert simlist to a NumPy array
simlist_array = np.array(simlist)

# Calculate the standard deviation
std_dev = np.std(simlist_array, axis=0)

print("Standard Deviation of similarity scores:", std_dev)

mean_sims = np.mean(np.array(simlist), axis=0)
#print("Mean similarity scores:", mean_sims)

# Save the mean_sims array to a file
#np.save('mean_sims.npy', mean_sims)

# Save the mean_sims array to a file
#np.save('std_dev_sims.npy', std_dev)