Skip to content

Commit afab651

Browse files
authored
Merge pull request #60 from michaelthwan/semantic_openai_native
Semantic openai native (de-faiss) / Model-based citation footnote
2 parents eda372b + 34e22e1 commit afab651

15 files changed

+449
-377
lines changed

playground/test_OpenAI_Embedding.py

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import os
2+
3+
import openai
4+
import pandas as pd
5+
import yaml
6+
from openai.embeddings_utils import get_embedding, cosine_similarity
7+
8+
from Util import get_project_root
9+
10+
BASE_MODEL = "text-embedding-ada-002" # default embedding of faiss-openai
11+
12+
13+
def search_using_cosine_similarity(df, query):
14+
query_embedding = get_embedding(query, engine=BASE_MODEL)
15+
df["similarity"] = df['embeddings'].apply(lambda x: cosine_similarity(x, query_embedding))
16+
17+
results = df.sort_values("similarity", ascending=False, ignore_index=True)
18+
19+
k = 5
20+
results = results.head(k)
21+
global sources
22+
sources = []
23+
for i in range(k):
24+
sources.append({'Page ' + str(results.iloc[i]['page']): results.iloc[i]['text'][:150] + '...'})
25+
print(sources)
26+
return results.head(k)
27+
28+
29+
def compute_embeddings(text, model="text-embedding-ada-002"):
30+
print(f'compute_embeddings() text: {text}')
31+
text = text.replace("\n", " ")
32+
return openai.Embedding.create(input=[text], model=model)['data'][0]['embedding']
33+
34+
35+
def search_similar(df: pd.DataFrame, target_text, n=3, pprint=True):
36+
print(f'search_similar() text: {target_text}')
37+
embedding = compute_embeddings(target_text, model=BASE_MODEL)
38+
df['similarities'] = df['embedding'].apply(lambda x: cosine_similarity(x, embedding))
39+
res = df.sort_values('similarities', ascending=False).head(n)
40+
return res, df
41+
42+
43+
def compute_embeddings_2(text_df, model=BASE_MODEL, chunk_size=1000):
44+
print(f'compute_embeddings_2() len(texts): {len(df)}')
45+
text_df['text'] = text_df['text'].apply(lambda x: x.replace("\n", " "))
46+
embeddings = []
47+
for i in range(0, len(texts), chunk_size):
48+
response = openai.Embedding.create(
49+
input=texts[i: i + chunk_size], engine=model
50+
)
51+
embeddings += [r["embedding"] for r in response["data"]]
52+
text_df['embedding'] = embeddings
53+
return text_df
54+
55+
56+
if __name__ == '__main__':
57+
# text_df = pd.read_csv(os.path.join(get_project_root(), 'src/text_df.csv'))
58+
texts = [
59+
"Discover the world of delicious beans with our premium selection.",
60+
"Try our savory bean soup recipe for a delicious and nutritious meal.",
61+
"Our roasted coffee beans are carefully selected for their rich and delicious flavor.",
62+
"Beans are not only delicious, but also a great source of protein and dietary fiber.",
63+
"Looking for a delicious vegan meal? Try our spicy black bean burger recipe.",
64+
65+
"The sky is blue and the sun is shining today.",
66+
"I need to go grocery shopping after work to pick up some milk and bread.",
67+
"Did you hear about the new movie that just came out? It's supposed to be really good.",
68+
"I'm planning a trip to Europe next summer and I'm so excited.",
69+
"My cat keeps meowing at me for no reason and it's driving me crazy.",
70+
]
71+
text_df = pd.DataFrame({'text': texts, 'docno': range(len(texts))})
72+
print(text_df.shape)
73+
74+
with open(os.path.join(get_project_root(), 'src/config/config.yaml')) as f:
75+
config = yaml.load(f, Loader=yaml.FullLoader)
76+
openai.api_key = config.get('openai_api').get('api_key')
77+
78+
# text_df = compute_embeddings(text_df)
79+
# result_df = search_using_cosine_similarity(text_df, 'what is chatgpt?')
80+
# print(result_df)
81+
82+
search_text = 'delicious beans'
83+
search_text = 'Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection Discover the world of delicious beans with our premium selection '
84+
85+
from pyinstrument import Profiler
86+
87+
profiler = Profiler()
88+
profiler.start()
89+
print("Sequential call mode:")
90+
text_df['embedding'] = text_df['text'].apply(lambda x: compute_embeddings(x, model=BASE_MODEL))
91+
res, text_df = search_similar(text_df, search_text, n=3)
92+
print(res)
93+
profiler.stop()
94+
profiler.print()
95+
96+
profiler = Profiler()
97+
profiler.start()
98+
print("Batch call mode:")
99+
text_df = compute_embeddings_2(text_df)
100+
res, text_df = search_similar(text_df, search_text, n=3)
101+
print(res)
102+
profiler.stop()
103+
profiler.print()

requirements.txt

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -9,7 +9,11 @@ Flask==2.2.3
99
requests==2.28.2
1010
gunicorn==20.1.0
1111

12-
# nlp
12+
# embedding
13+
matplotlib==3.7.1
14+
plotly==5.13.1
15+
scipy==1.10.1
16+
scikit-learn==1.2.1
1317

1418
# doc extraction
1519
python-docx==0.8.11
@@ -18,11 +22,3 @@ python-pptx==0.6.21
1822
# html extraction
1923
beautifulsoup4==4.11.2
2024
trafilatura==1.4.1
21-
22-
# doc indexer1
23-
# python-terrier==0.9.2
24-
25-
# doc indexer2
26-
faiss-cpu==1.7.3
27-
langchain==0.0.95
28-

src/FootnoteService.py

Lines changed: 0 additions & 154 deletions
This file was deleted.

0 commit comments

Comments
 (0)