Spaces:
Sleeping
Sleeping
Upload 2 files
Browse files- app.py +54 -0
- requirments.txt +3 -0
app.py
ADDED
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import time
|
2 |
+
import gradio as gr
|
3 |
+
|
4 |
+
import asyncio
|
5 |
+
from pymongo import MongoClient
|
6 |
+
from langchain.vectorstores import MongoDBAtlasVectorSearch
|
7 |
+
from langchain.embeddings import OpenAIEmbeddings
|
8 |
+
from langchain.llms import OpenAI
|
9 |
+
from langchain.prompts import PromptTemplate
|
10 |
+
from langchain.chains import LLMChain
|
11 |
+
import json
|
12 |
+
|
13 |
+
|
14 |
+
## Connect to MongoDB Atlas local cluster
|
15 |
+
MONGODB_ATLAS_CLUSTER_URI = os.getenv('MONGODB_ATLAS_CLUSTER_URI')
|
16 |
+
client = MongoClient(MONGODB_ATLAS_CLUSTER_URI)
|
17 |
+
db_name = 'sample_mflix'
|
18 |
+
collection_name = 'movies'
|
19 |
+
collection = client[db_name][collection_name]
|
20 |
+
|
21 |
+
## Create a collection and insert data
|
22 |
+
print ('Creating collection movies')
|
23 |
+
client[db_name].create_collection(collection_name)
|
24 |
+
|
25 |
+
## Create a vector search index
|
26 |
+
print ('Creating vector search index')
|
27 |
+
collection.create_search_index(model={"definition": {"mappings":{
|
28 |
+
"dynamic":True,
|
29 |
+
"fields": {
|
30 |
+
"plot_embedding": {
|
31 |
+
"type": "knnVector",
|
32 |
+
"dimensions": 1536,
|
33 |
+
"similarity": "euclidean"
|
34 |
+
}
|
35 |
+
}
|
36 |
+
}}, "name":'default'})
|
37 |
+
|
38 |
+
# sleep for minute
|
39 |
+
print ('Waiting for vector index on field "embedding" to be created')
|
40 |
+
time.sleep(60)
|
41 |
+
|
42 |
+
vector_store = MongoDBAtlasVectorSearch(embedding=OpenAIEmbeddings(), collection=collection, index_name='default', text_key='plot', embedding_key='plot_embedding')
|
43 |
+
|
44 |
+
def get_movies(message, history):
|
45 |
+
movies = vector_store.similarity_search(message, 3)
|
46 |
+
for movie in movies:
|
47 |
+
for i in range(len(movie.metadata['title'])):
|
48 |
+
time.sleep(0.05)
|
49 |
+
yield "Movie " + i + " : Title - " + movie.metadata['title'][: i+1]
|
50 |
+
|
51 |
+
demo = gr.ChatInterface(get_movies, examples=["What movies are scary?", "Find me a comedy", "Movies for kids"], title="Movies Atlas Vector Search", submit_btn="Search").queue()
|
52 |
+
|
53 |
+
if __name__ == "__main__":
|
54 |
+
demo.launch()
|
requirments.txt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
pymongo
|
2 |
+
langchain
|
3 |
+
openai
|