You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
fromopenaiimportOpenAIimportpandasaspdimportnumpyasnpimportosimportjsonfromdotenvimportload_dotenvload_dotenv()
# create .env file and add OPENAI_API_KEY, it should start with sk-...OPENAI_API_KEY=os.getenv('OPENAI_API_KEY')
# Instead of using OpenAI API to create text embeddings, you can also use# Open source models such as: https://huggingface.co/Snowflake/snowflake-arctic-embed-s# Very easy to import and use using huggingface model API; just change Pinecone vector storage dimensions accordingly
client=OpenAI()
# set the api keyclient.api_key=OPENAI_API_KEY# This function takes a text and returns the embedding of the text from openaidefmy_get_embedding(text, model="text-embedding-3-small"):
text=text.replace("\n", " ")
text=''.join(filter(str.isalnum, text))
returnclient.embeddings.create(input= [text], model=model).data[0].embedding
# Create a dataframe from the json filespath_to_json='./videos/'json_files= [pos_jsonforpos_jsoninos.listdir(path_to_json) ifpos_json.endswith('.json')]
# the ID field will contain the date and the video ID that is unique for each video and can be combined with https://www.tiktokv.com/share/video/... to get the video URLdata=dict()
titles= []
foriinjson_files:
withopen(path_to_json+i) asjf:
j=json.load(jf)
txt=''try:
txt=';'.join(j['itemInfo']['itemStruct']['suggestedWords'])
exceptExceptionas_:
txt=''try:
txt+=j['itemInfo']['itemStruct']['desc'] +';'+j['shareMeta']['title']
titles.append(j['shareMeta']['title'])
exceptExceptionas_:
continuedata[i] =txtdf= {'id':data.keys(),'text':data.values(),'title': titles}
df=pd.DataFrame.from_dict(df)
# Example of the dataframeprint(df[['id','title']].head())
id \
0 2020-12-11T16-36-48_6904707844294053126.json
1 2020-12-15T17-25-26_6905454041074011398.json
2 2020-12-15T19-14-43_6897881517813402885.json
3 2020-12-15T20-01-31_6901495881992867077.json
4 2020-12-15T20-09-37_6898107668905331974.json
title
0 Matt Lorion on TikTok
1 Wonsulting | Career Tipsππ‘ on TikTok
2 unstoppablegiggle on TikTok
3 Sam - Your Career Bestie on TikTok
4 Mariella Mahal on TikTok
# Lets remove the " on TikTok" from the titledf['title'] =df['title'].str.replace(' on TikTok','')
print(df[['id','title']].head())
id title
0 2020-12-11T16-36-48_6904707844294053126.json Matt Lorion
1 2020-12-15T17-25-26_6905454041074011398.json Wonsulting | Career Tipsππ‘
2 2020-12-15T19-14-43_6897881517813402885.json unstoppablegiggle
3 2020-12-15T20-01-31_6901495881992867077.json Sam - Your Career Bestie
4 2020-12-15T20-09-37_6898107668905331974.json Mariella Mahal
# This will get the embeddings of the textembeddings= []
fortxtindf['text']:
embeddings.append(my_get_embedding(txt))
# Save the embeddings to a filedf['embeddings'] =embeddingsdf.to_csv('vids_with_embeds.csv',index=False)
# Now you have a dataframe with the embeddings! Note that the links of the videos are in the 'id' column, seperated by the underscoreprint(df.head())
print(len(df['embeddings'][0]))
id \
0 2020-12-11T16-36-48_6904707844294053126.json
1 2020-12-15T17-25-26_6905454041074011398.json
2 2020-12-15T19-14-43_6897881517813402885.json
3 2020-12-15T20-01-31_6901495881992867077.json
4 2020-12-15T20-09-37_6898107668905331974.json
text \
0 Trading Motivation;trading places;Trading Spac...
1 How do you get a referral for companies like i...
2 Reply to @bankai_zabimaru #greenscreen #stemli...
3 How to respond (and crush it) when an intervie...
4 i havenβt paid for books in 2 years - like for...
title \
0 Matt Lorion
1 Wonsulting | Career Tipsππ‘
2 unstoppablegiggle
3 Sam - Your Career Bestie
4 Mariella Mahal
embeddings
0 [0.004208823665976524, -0.03823400288820267, 0...
1 [-0.0031721279956400394, 0.004200569353997707,...
2 [0.017734628170728683, -0.024280162528157234, ...
3 [-0.003541965037584305, -0.03863702714443207, ...
4 [-0.013438946567475796, -0.01910446211695671, ...
1536
i havenβt paid for books in 2 years - like for...
Mariella Mahal
[-0.013438946567475796, -0.01910446211695671, ...
new_embeddings= []
# convert the string representation of the lists to a list of floatsprint(type(df['embeddings'].iloc[0]))
foreinembeddings:
new_embeddings.append([float(x) forxine[1:-1].split(',')])
df['embeddings'] =new_embeddingsprint(type(df['embeddings'].iloc[0]))
# print(df.head())# replace NaN titles with Anonymus
<class 'str'>
<class 'list'>
# Convert the string representation of the list to a list of floats# print(type(df['embeddings'].iloc[0]))# df["embeddings"] = df.embeddings.apply(eval).apply(np.array)# print(type(df['embeddings'].iloc[0]))df['title'] =df['title'].fillna('Anonymus')
print("Dimention of the embeddings: ",len(res['embeddings'].iloc[0]))
res.head()
Dimention of the embeddings: 1536
id
text
title
embeddings
similarities
4
2020-12-15T20-09-37_6898107668905331974.json
i havenβt paid for books in 2 years - like for...
Mariella Mahal
[-0.013438946567475796, -0.01910446211695671, ...
0.293667
146
2023-03-17T21-02-09_7211241979890404650.json
kuru toga;kuru toga mechanical pencil;best mec...
bungu.store
[0.024209968745708466, 0.009360017254948616, -...
0.236675
11
2020-12-28T20-41-32_6908485370212551941.json
Since people been asking for Manhwa recommenda...
breezylouie
[0.044516436755657196, 0.019246326759457588, -...
0.207206
The search is working! All the results are related to the search word "book". Take note of the dimention of the embeddings
id
text
title
embeddings
similarities
4
2020-12-15T20-09-37_6898107668905331974.json
i havenβt paid for books in 2 years - like for...
Mariella Mahal
[-0.013438946567475796, -0.01910446211695671, ...
0.293667
146
2023-03-17T21-02-09_7211241979890404650.json
kuru toga;kuru toga mechanical pencil;best mec...
bungu.store
[0.024209968745708466, 0.009360017254948616, -...
0.236675
11
2020-12-28T20-41-32_6908485370212551941.json
Since people been asking for Manhwa recommenda...
breezylouie
[0.044516436755657196, 0.019246326759457588, -...
0.207206
Upload embeddings into pinecone
Create an account on pinecone.io and create a free index, ensure the metric of the index is cosine and the dimensions is the same as the one noted above (1536 if using "text-embedding-3-small")
f:\savedtt\tiktok-save\.venv\lib\site-packages\pinecone\data\index.py:1: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html
from tqdm.autonotebook import tqdm
pc=Pinecone(api_key=PINECONE_API_KEY)
# Make this the name of the index you created on the Pinecone dashboardname_of_index="tt"# name_of_index = "quickstart"index=pc.Index(name_of_index)
# upserting a list of tuples of the form (id, embedding)vals= []
foriinrange(len(df)):
vals.append(({"id":df['id'][i], "values":df['embeddings'][i],"metadata":{'title':df['title'][i],'text':df['text'][i]}}))
fromtqdm.autoimporttqdmforbatchintqdm(range(0, len(vals), 50)):
print(f"Upserting batch {batch} to {batch+50}")
index.upsert(vals[batch:batch+50],namespace='tt')
# If you forgot to add a metadata field, you can update it using the following code# I forgot to add the text field to the metadatafromtqdm.autoimporttqdmforbatchintqdm(range(0, len(vals))):
index.update(id=vals[i]['id'],namespace='tt',set_metadata={'text':vals[i]['metadata']['text']})
# test with a querybook_embed=my_get_embedding("books")