Spaces:
Sleeping
Sleeping
Update helpers.py
Browse files- helpers.py +145 -145
helpers.py
CHANGED
@@ -1,146 +1,146 @@
|
|
1 |
-
from transformers import AutoTokenizer, AutoModel, AutoImageProcessor
|
2 |
-
from sentence_transformers import SentenceTransformer
|
3 |
-
import torch
|
4 |
-
import torch.nn.functional as F
|
5 |
-
from PIL import Image
|
6 |
-
import requests
|
7 |
-
import os
|
8 |
-
import json
|
9 |
-
import math
|
10 |
-
import re
|
11 |
-
import pandas as pd
|
12 |
-
import numpy as np
|
13 |
-
from omeka_s_api_client import OmekaSClient,OmekaSClientError
|
14 |
-
from typing import List, Dict, Any, Union
|
15 |
-
import io
|
16 |
-
from dotenv import load_dotenv
|
17 |
-
|
18 |
-
# env var
|
19 |
-
load_dotenv(os.path.join(os.getcwd(), ".env"))
|
20 |
-
HF_TOKEN = os.environ.get("HF_TOKEN")
|
21 |
-
|
22 |
-
# Nomic vison model
|
23 |
-
processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5")
|
24 |
-
vision_model = AutoModel.from_pretrained("nomic-ai/nomic-embed-vision-v1.5", trust_remote_code=True)
|
25 |
-
|
26 |
-
# Nomic text model
|
27 |
-
text_model = SentenceTransformer("nomic-ai/nomic-embed-text-v1.5", trust_remote_code=True, token=HF_TOKEN)
|
28 |
-
|
29 |
-
def image_url_to_pil(url: str, max_size=(512, 512)) -> Image:
|
30 |
-
"""
|
31 |
-
Ex usage : image_blobs = df["image_url"].apply(image_url_to_pil).tolist()
|
32 |
-
"""
|
33 |
-
response = requests.get(url, stream=True, timeout=5)
|
34 |
-
response.raise_for_status()
|
35 |
-
image = Image.open(io.BytesIO(response.content)).convert("RGB")
|
36 |
-
image.thumbnail(max_size, Image.Resampling.LANCZOS)
|
37 |
-
return image
|
38 |
-
|
39 |
-
def generate_img_embed(images_urls, batch_size=20):
|
40 |
-
"""Generate image embeddings in batches to manage memory usage.
|
41 |
-
|
42 |
-
Args:
|
43 |
-
images_urls (list): List of image URLs
|
44 |
-
batch_size (int): Number of images to process at once
|
45 |
-
"""
|
46 |
-
all_embeddings = []
|
47 |
-
|
48 |
-
for i in range(0, len(images_urls), batch_size):
|
49 |
-
batch_urls = images_urls[i:i + batch_size]
|
50 |
-
images = [image_url_to_pil(image_url) for image_url in batch_urls]
|
51 |
-
inputs = processor(images, return_tensors="pt")
|
52 |
-
img_emb = vision_model(**inputs).last_hidden_state
|
53 |
-
img_embeddings = F.normalize(img_emb[:, 0], p=2, dim=1)
|
54 |
-
all_embeddings.append(img_embeddings.detach().numpy())
|
55 |
-
|
56 |
-
return np.vstack(all_embeddings)
|
57 |
-
|
58 |
-
def generate_text_embed(sentences: List, batch_size=64):
|
59 |
-
"""Generate text embeddings in batches to manage memory usage.
|
60 |
-
|
61 |
-
Args:
|
62 |
-
sentences (List): List of text strings to encode
|
63 |
-
batch_size (int): Number of sentences to process at once
|
64 |
-
"""
|
65 |
-
all_embeddings = []
|
66 |
-
|
67 |
-
for i in range(0, len(sentences), batch_size):
|
68 |
-
batch_sentences = sentences[i:i + batch_size]
|
69 |
-
embeddings = text_model.encode(batch_sentences)
|
70 |
-
all_embeddings.append(embeddings)
|
71 |
-
|
72 |
-
return np.vstack(all_embeddings)
|
73 |
-
|
74 |
-
def add_concatenated_text_field_exclude_keys(item_dict, keys_to_exclude=None, text_field_key="text", pair_separator=" - "):
|
75 |
-
if not isinstance(item_dict, dict):
|
76 |
-
raise TypeError("Input must be a dictionary.")
|
77 |
-
if keys_to_exclude is None:
|
78 |
-
keys_to_exclude = set() # Default to empty set
|
79 |
-
else:
|
80 |
-
keys_to_exclude = set(keys_to_exclude) # Ensure it's a set for efficient lookup
|
81 |
-
|
82 |
-
# Add the target text key to the exclusion set automatically
|
83 |
-
keys_to_exclude.add(text_field_key)
|
84 |
-
|
85 |
-
formatted_pairs = []
|
86 |
-
for key, value in item_dict.items():
|
87 |
-
# 1. Skip any key in the exclusion set
|
88 |
-
if key in keys_to_exclude:
|
89 |
-
continue
|
90 |
-
|
91 |
-
# 2. Check for empty/invalid values (same logic as before)
|
92 |
-
is_empty_or_invalid = False
|
93 |
-
if value is None: is_empty_or_invalid = True
|
94 |
-
elif isinstance(value, float) and math.isnan(value): is_empty_or_invalid = True
|
95 |
-
elif isinstance(value, (str, list, tuple, dict)) and len(value) == 0: is_empty_or_invalid = True
|
96 |
-
|
97 |
-
# 3. Format and add if valid
|
98 |
-
if not is_empty_or_invalid:
|
99 |
-
formatted_pairs.append(f"{str(key)}: {str(value)}")
|
100 |
-
|
101 |
-
concatenated_text = f"search_document: {pair_separator.join(formatted_pairs)}"
|
102 |
-
item_dict[text_field_key] = concatenated_text
|
103 |
-
return item_dict
|
104 |
-
|
105 |
-
def prepare_df_atlas(df: pd.DataFrame, id_col='id', images_col='images_urls'):
|
106 |
-
|
107 |
-
# Drop completely empty columns
|
108 |
-
#df = df.dropna(axis=1, how='all')
|
109 |
-
|
110 |
-
# Fill remaining nulls with empty strings
|
111 |
-
#df = df.fillna('')
|
112 |
-
|
113 |
-
# Ensure ID column exists
|
114 |
-
if id_col not in df.columns:
|
115 |
-
df[id_col] = [f'{i}' for i in range(len(df))]
|
116 |
-
|
117 |
-
# Ensure indexed field exists and is not empty
|
118 |
-
#if indexed_col not in df.columns:
|
119 |
-
# df[indexed_col] = ''
|
120 |
-
|
121 |
-
#df[images_col] = df[images_col].apply(lambda x: [x[0]] if isinstance(x, list) and len(x) > 1 else x if isinstance(x, list) else [x])
|
122 |
-
df[images_col] = df[images_col].apply(lambda x: x[0] if isinstance(x, list) else x)
|
123 |
-
|
124 |
-
# Optional: force all to string (can help with weird dtypes)
|
125 |
-
for col in df.columns:
|
126 |
-
df[col] = df[col].astype(str)
|
127 |
-
|
128 |
-
return df
|
129 |
-
|
130 |
-
def remove_key_value_from_dict(list_of_dict, key_to_remove):
|
131 |
-
new_list = []
|
132 |
-
for dictionary in list_of_dict:
|
133 |
-
new_dict = dictionary.copy() # Create a copy to avoid modifying the original list
|
134 |
-
if key_to_remove in new_dict:
|
135 |
-
del new_dict[key_to_remove]
|
136 |
-
new_list.append(new_dict)
|
137 |
-
return new_list
|
138 |
-
|
139 |
-
def remove_key_value_from_dict(input_dict, key_to_remove='text'):
|
140 |
-
if not isinstance(input_dict, dict):
|
141 |
-
raise TypeError("Input must be a dictionary.")
|
142 |
-
|
143 |
-
if key_to_remove in input_dict:
|
144 |
-
del input_dict[key_to_remove]
|
145 |
-
|
146 |
return input_dict
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModel, AutoImageProcessor
|
2 |
+
from sentence_transformers import SentenceTransformer
|
3 |
+
import torch
|
4 |
+
import torch.nn.functional as F
|
5 |
+
from PIL import Image
|
6 |
+
import requests
|
7 |
+
import os
|
8 |
+
import json
|
9 |
+
import math
|
10 |
+
import re
|
11 |
+
import pandas as pd
|
12 |
+
import numpy as np
|
13 |
+
from omeka_s_api_client import OmekaSClient,OmekaSClientError
|
14 |
+
from typing import List, Dict, Any, Union
|
15 |
+
import io
|
16 |
+
from dotenv import load_dotenv
|
17 |
+
|
18 |
+
# env var
|
19 |
+
load_dotenv(os.path.join(os.getcwd(), ".env"))
|
20 |
+
HF_TOKEN = os.environ.get("HF_TOKEN")
|
21 |
+
|
22 |
+
# Nomic vison model
|
23 |
+
processor = AutoImageProcessor.from_pretrained("nomic-ai/nomic-embed-vision-v1.5")
|
24 |
+
vision_model = AutoModel.from_pretrained("nomic-ai/nomic-embed-vision-v1.5", trust_remote_code=True)
|
25 |
+
|
26 |
+
# Nomic text model
|
27 |
+
text_model = SentenceTransformer("nomic-ai/nomic-embed-text-v1.5", trust_remote_code=True, token=HF_TOKEN)
|
28 |
+
|
29 |
+
def image_url_to_pil(url: str, max_size=(512, 512)) -> Image:
|
30 |
+
"""
|
31 |
+
Ex usage : image_blobs = df["image_url"].apply(image_url_to_pil).tolist()
|
32 |
+
"""
|
33 |
+
response = requests.get(url, stream=True, timeout=5)
|
34 |
+
response.raise_for_status()
|
35 |
+
image = Image.open(io.BytesIO(response.content)).convert("RGB")
|
36 |
+
image.thumbnail(max_size, Image.Resampling.LANCZOS)
|
37 |
+
return image
|
38 |
+
|
39 |
+
def generate_img_embed(images_urls, batch_size=20):
|
40 |
+
"""Generate image embeddings in batches to manage memory usage.
|
41 |
+
|
42 |
+
Args:
|
43 |
+
images_urls (list): List of image URLs
|
44 |
+
batch_size (int): Number of images to process at once
|
45 |
+
"""
|
46 |
+
all_embeddings = []
|
47 |
+
|
48 |
+
for i in range(0, len(images_urls), batch_size):
|
49 |
+
batch_urls = images_urls[i:i + batch_size]
|
50 |
+
images = [image_url_to_pil(image_url) for image_url in batch_urls]
|
51 |
+
inputs = processor(images, return_tensors="pt")
|
52 |
+
img_emb = vision_model(**inputs).last_hidden_state
|
53 |
+
img_embeddings = F.normalize(img_emb[:, 0], p=2, dim=1)
|
54 |
+
all_embeddings.append(img_embeddings.detach().numpy())
|
55 |
+
|
56 |
+
return np.vstack(all_embeddings)
|
57 |
+
|
58 |
+
def generate_text_embed(sentences: List, batch_size=64):
|
59 |
+
"""Generate text embeddings in batches to manage memory usage.
|
60 |
+
|
61 |
+
Args:
|
62 |
+
sentences (List): List of text strings to encode
|
63 |
+
batch_size (int): Number of sentences to process at once
|
64 |
+
"""
|
65 |
+
all_embeddings = []
|
66 |
+
|
67 |
+
for i in range(0, len(sentences), batch_size):
|
68 |
+
batch_sentences = sentences[i:i + batch_size]
|
69 |
+
embeddings = text_model.encode(batch_sentences)
|
70 |
+
all_embeddings.append(embeddings)
|
71 |
+
|
72 |
+
return np.vstack(all_embeddings)
|
73 |
+
|
74 |
+
def add_concatenated_text_field_exclude_keys(item_dict, keys_to_exclude=None, text_field_key="text", pair_separator=" - "):
|
75 |
+
if not isinstance(item_dict, dict):
|
76 |
+
raise TypeError("Input must be a dictionary.")
|
77 |
+
if keys_to_exclude is None:
|
78 |
+
keys_to_exclude = set() # Default to empty set
|
79 |
+
else:
|
80 |
+
keys_to_exclude = set(keys_to_exclude) # Ensure it's a set for efficient lookup
|
81 |
+
|
82 |
+
# Add the target text key to the exclusion set automatically
|
83 |
+
keys_to_exclude.add(text_field_key)
|
84 |
+
|
85 |
+
formatted_pairs = []
|
86 |
+
for key, value in item_dict.items():
|
87 |
+
# 1. Skip any key in the exclusion set
|
88 |
+
if key in keys_to_exclude:
|
89 |
+
continue
|
90 |
+
|
91 |
+
# 2. Check for empty/invalid values (same logic as before)
|
92 |
+
is_empty_or_invalid = False
|
93 |
+
if value is None: is_empty_or_invalid = True
|
94 |
+
elif isinstance(value, float) and math.isnan(value): is_empty_or_invalid = True
|
95 |
+
elif isinstance(value, (str, list, tuple, dict)) and len(value) == 0: is_empty_or_invalid = True
|
96 |
+
|
97 |
+
# 3. Format and add if valid
|
98 |
+
if not is_empty_or_invalid:
|
99 |
+
formatted_pairs.append(f"{str(key)}: {str(value)}")
|
100 |
+
|
101 |
+
concatenated_text = f"search_document: {pair_separator.join(formatted_pairs)}"
|
102 |
+
item_dict[text_field_key] = concatenated_text
|
103 |
+
return item_dict
|
104 |
+
|
105 |
+
def prepare_df_atlas(df: pd.DataFrame, id_col='id', images_col='images_urls'):
|
106 |
+
|
107 |
+
# Drop completely empty columns
|
108 |
+
#df = df.dropna(axis=1, how='all')
|
109 |
+
|
110 |
+
# Fill remaining nulls with empty strings
|
111 |
+
#df = df.fillna('')
|
112 |
+
|
113 |
+
# Ensure ID column exists
|
114 |
+
if id_col not in df.columns:
|
115 |
+
df[id_col] = [f'{i}' for i in range(len(df))]
|
116 |
+
|
117 |
+
# Ensure indexed field exists and is not empty
|
118 |
+
#if indexed_col not in df.columns:
|
119 |
+
# df[indexed_col] = ''
|
120 |
+
|
121 |
+
#df[images_col] = df[images_col].apply(lambda x: [x[0]] if isinstance(x, list) and len(x) > 1 else x if isinstance(x, list) else [x])
|
122 |
+
df[images_col] = df[images_col].apply(lambda x: x[0] if isinstance(x, list) else x)
|
123 |
+
|
124 |
+
# Optional: force all to string (can help with weird dtypes)
|
125 |
+
for col in df.columns:
|
126 |
+
df[col] = df[col].astype(str)
|
127 |
+
|
128 |
+
return df
|
129 |
+
|
130 |
+
def remove_key_value_from_dict(list_of_dict, key_to_remove):
|
131 |
+
new_list = []
|
132 |
+
for dictionary in list_of_dict:
|
133 |
+
new_dict = dictionary.copy() # Create a copy to avoid modifying the original list
|
134 |
+
if key_to_remove in new_dict:
|
135 |
+
del new_dict[key_to_remove]
|
136 |
+
new_list.append(new_dict)
|
137 |
+
return new_list
|
138 |
+
|
139 |
+
def remove_key_value_from_dict(input_dict, key_to_remove='text'):
|
140 |
+
if not isinstance(input_dict, dict):
|
141 |
+
raise TypeError("Input must be a dictionary.")
|
142 |
+
|
143 |
+
if key_to_remove in input_dict:
|
144 |
+
del input_dict[key_to_remove]
|
145 |
+
|
146 |
return input_dict
|