Spaces:
Running
on
CPU Upgrade
Running
on
CPU Upgrade
Commit
•
e8f13e9
1
Parent(s):
35c26f5
draft
Browse files- load_data.py +138 -0
load_data.py
ADDED
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import chromadb
|
2 |
+
import platform
|
3 |
+
import polars as pl
|
4 |
+
import polars as pl
|
5 |
+
from chromadb.utils import embedding_functions
|
6 |
+
from typing import List, Tuple, Optional
|
7 |
+
from huggingface_hub import InferenceClient
|
8 |
+
from tqdm.contrib.concurrent import thread_map
|
9 |
+
from huggingface_hub import login
|
10 |
+
from dotenv import load_dotenv
|
11 |
+
import os
|
12 |
+
from datetime import datetime, timedelta
|
13 |
+
import stamina
|
14 |
+
import requests
|
15 |
+
import polars as pl
|
16 |
+
from typing import Literal
|
17 |
+
|
18 |
+
load_dotenv()
|
19 |
+
HF_TOKEN = os.getenv("HF_TOKEN")
|
20 |
+
|
21 |
+
|
22 |
+
def get_save_path() -> Literal["chroma/"] | Literal["/data/chroma/"]:
|
23 |
+
return "chroma/" if platform.system() == "Darwin" else "/data/chroma/"
|
24 |
+
|
25 |
+
|
26 |
+
save_path = get_save_path()
|
27 |
+
|
28 |
+
|
29 |
+
chroma_client = chromadb.PersistentClient(
|
30 |
+
path=save_path,
|
31 |
+
)
|
32 |
+
sentence_transformer_ef = embedding_functions.SentenceTransformerEmbeddingFunction(
|
33 |
+
model_name="Snowflake/snowflake-arctic-embed-m-long", trust_remote_code=True
|
34 |
+
)
|
35 |
+
collection = chroma_client.create_collection(
|
36 |
+
name="dataset_cards", get_or_create=True, embedding_function=sentence_transformer_ef
|
37 |
+
)
|
38 |
+
|
39 |
+
|
40 |
+
def get_last_modified_in_collection() -> datetime | None:
|
41 |
+
all_items = collection.get(
|
42 |
+
include=[
|
43 |
+
"metadatas",
|
44 |
+
]
|
45 |
+
)
|
46 |
+
if last_modified := [
|
47 |
+
datetime.fromisoformat(item["last_modified"]) for item in all_items["metadatas"]
|
48 |
+
]:
|
49 |
+
return max(last_modified)
|
50 |
+
else:
|
51 |
+
return None
|
52 |
+
|
53 |
+
|
54 |
+
def parse_markdown_column(
|
55 |
+
df: pl.DataFrame, markdown_column: str, dataset_id_column: str
|
56 |
+
) -> pl.DataFrame:
|
57 |
+
return df.with_columns(
|
58 |
+
parsed_markdown=(
|
59 |
+
pl.col(markdown_column)
|
60 |
+
.str.extract(r"(?s)^---.*?---\s*(.*)", group_index=1)
|
61 |
+
.fill_null(pl.col(markdown_column))
|
62 |
+
.str.strip_chars()
|
63 |
+
),
|
64 |
+
prepended_markdown=(
|
65 |
+
pl.concat_str(
|
66 |
+
[
|
67 |
+
pl.lit("Dataset ID "),
|
68 |
+
pl.col(dataset_id_column).cast(pl.Utf8),
|
69 |
+
pl.lit("\n\n"),
|
70 |
+
pl.col(markdown_column)
|
71 |
+
.str.extract(r"(?s)^---.*?---\s*(.*)", group_index=1)
|
72 |
+
.fill_null(pl.col(markdown_column))
|
73 |
+
.str.strip_chars(),
|
74 |
+
]
|
75 |
+
)
|
76 |
+
),
|
77 |
+
)
|
78 |
+
|
79 |
+
|
80 |
+
def load_cards(
|
81 |
+
min_len: int = 50,
|
82 |
+
min_likes: int | None = None,
|
83 |
+
last_modified: Optional[datetime] = None,
|
84 |
+
) -> (
|
85 |
+
None
|
86 |
+
| Tuple[
|
87 |
+
List[str],
|
88 |
+
List[str],
|
89 |
+
List[datetime],
|
90 |
+
]
|
91 |
+
):
|
92 |
+
df = pl.read_parquet(
|
93 |
+
"hf://datasets/librarian-bots/dataset_cards_with_metadata_with_embeddings/data/train-00000-of-00001.parquet"
|
94 |
+
)
|
95 |
+
df = parse_markdown_column(df, "card", "datasetId")
|
96 |
+
df = df.with_columns(pl.col("parsed_markdown").str.len_chars().alias("card_len"))
|
97 |
+
print(df)
|
98 |
+
df = df.filter(pl.col("card_len") > min_len)
|
99 |
+
print(df)
|
100 |
+
if min_likes:
|
101 |
+
df = df.filter(pl.col("likes") > min_likes)
|
102 |
+
if last_modified:
|
103 |
+
df = df.filter(pl.col("last_modified") > last_modified)
|
104 |
+
if len(df) == 0:
|
105 |
+
return None
|
106 |
+
|
107 |
+
cards = df.get_column("prepended_markdown").to_list()
|
108 |
+
model_ids = df.get_column("datasetId").to_list()
|
109 |
+
last_modifieds = df.get_column("last_modified").to_list()
|
110 |
+
return cards, model_ids, last_modifieds
|
111 |
+
|
112 |
+
|
113 |
+
client = InferenceClient(
|
114 |
+
model="https://pqzap00ebpl1ydt4.us-east-1.aws.endpoints.huggingface.cloud",
|
115 |
+
token=HF_TOKEN,
|
116 |
+
)
|
117 |
+
|
118 |
+
|
119 |
+
@stamina.retry(on=requests.HTTPError, attempts=3, wait_initial=10)
|
120 |
+
def embed_card(text):
|
121 |
+
text = text[:8192]
|
122 |
+
return client.feature_extraction(text)
|
123 |
+
|
124 |
+
|
125 |
+
most_recent = get_last_modified_in_collection()
|
126 |
+
|
127 |
+
if data := load_cards(min_len=200, min_likes=None, last_modified=most_recent):
|
128 |
+
cards, model_ids, last_modifieds = data
|
129 |
+
print("mapping...")
|
130 |
+
results = thread_map(embed_card, cards)
|
131 |
+
collection.upsert(
|
132 |
+
ids=model_ids,
|
133 |
+
embeddings=[embedding.tolist()[0] for embedding in results],
|
134 |
+
metadatas=[{"last_modified": str(lm)} for lm in last_modifieds],
|
135 |
+
)
|
136 |
+
print("done")
|
137 |
+
else:
|
138 |
+
print("no new data")
|