code
stringlengths
193
97.3k
apis
sequencelengths
1
8
extract_api
stringlengths
113
214k
import lancedb from langchain.vectorstores import LanceDB from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings def test_lancedb() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1", "text 2", "item 3"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) result = store.similarity_search("text 1") result_texts = [doc.page_content for doc in result] assert "text 1" in result_texts def test_lancedb_add_texts() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) store.add_texts(["text 2"]) result = store.similarity_search("text 2") result_texts = [doc.page_content for doc in result] assert "text 2" in result_texts
[ "lancedb.connect" ]
[((186, 202), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (200, 202), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((212, 243), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (227, 243), False, 'import lancedb\n'), ((563, 589), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (570, 589), False, 'from langchain.vectorstores import LanceDB\n'), ((786, 802), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (800, 802), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((812, 843), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (827, 843), False, 'import lancedb\n'), ((1143, 1169), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (1150, 1169), False, 'from langchain.vectorstores import LanceDB\n')]
import lancedb from langchain.vectorstores import LanceDB from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings def test_lancedb() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1", "text 2", "item 3"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) result = store.similarity_search("text 1") result_texts = [doc.page_content for doc in result] assert "text 1" in result_texts def test_lancedb_add_texts() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) store.add_texts(["text 2"]) result = store.similarity_search("text 2") result_texts = [doc.page_content for doc in result] assert "text 2" in result_texts
[ "lancedb.connect" ]
[((186, 202), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (200, 202), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((212, 243), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (227, 243), False, 'import lancedb\n'), ((563, 589), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (570, 589), False, 'from langchain.vectorstores import LanceDB\n'), ((786, 802), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (800, 802), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((812, 843), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (827, 843), False, 'import lancedb\n'), ((1143, 1169), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (1150, 1169), False, 'from langchain.vectorstores import LanceDB\n')]
import lancedb from langchain.vectorstores import LanceDB from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings def test_lancedb() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1", "text 2", "item 3"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) result = store.similarity_search("text 1") result_texts = [doc.page_content for doc in result] assert "text 1" in result_texts def test_lancedb_add_texts() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) store.add_texts(["text 2"]) result = store.similarity_search("text 2") result_texts = [doc.page_content for doc in result] assert "text 2" in result_texts
[ "lancedb.connect" ]
[((186, 202), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (200, 202), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((212, 243), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (227, 243), False, 'import lancedb\n'), ((563, 589), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (570, 589), False, 'from langchain.vectorstores import LanceDB\n'), ((786, 802), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (800, 802), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((812, 843), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (827, 843), False, 'import lancedb\n'), ((1143, 1169), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (1150, 1169), False, 'from langchain.vectorstores import LanceDB\n')]
import lancedb from langchain.vectorstores import LanceDB from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings def test_lancedb() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1", "text 2", "item 3"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) result = store.similarity_search("text 1") result_texts = [doc.page_content for doc in result] assert "text 1" in result_texts def test_lancedb_add_texts() -> None: embeddings = FakeEmbeddings() db = lancedb.connect("/tmp/lancedb") texts = ["text 1"] vectors = embeddings.embed_documents(texts) table = db.create_table( "my_table", data=[ {"vector": vectors[idx], "id": text, "text": text} for idx, text in enumerate(texts) ], mode="overwrite", ) store = LanceDB(table, embeddings) store.add_texts(["text 2"]) result = store.similarity_search("text 2") result_texts = [doc.page_content for doc in result] assert "text 2" in result_texts
[ "lancedb.connect" ]
[((186, 202), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (200, 202), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((212, 243), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (227, 243), False, 'import lancedb\n'), ((563, 589), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (570, 589), False, 'from langchain.vectorstores import LanceDB\n'), ((786, 802), 'tests.integration_tests.vectorstores.fake_embeddings.FakeEmbeddings', 'FakeEmbeddings', ([], {}), '()\n', (800, 802), False, 'from tests.integration_tests.vectorstores.fake_embeddings import FakeEmbeddings\n'), ((812, 843), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (827, 843), False, 'import lancedb\n'), ((1143, 1169), 'langchain.vectorstores.LanceDB', 'LanceDB', (['table', 'embeddings'], {}), '(table, embeddings)\n', (1150, 1169), False, 'from langchain.vectorstores import LanceDB\n')]
import argparse from pprint import pprint import pandas as pd from mlx_lm import generate, load import lancedb.embeddings.gte TEMPLATE = """You are a helpful, respectful and honest assistant. Always answer as helpfully as possible using the context text provided. Your answers should only answer the question once and not have any text after the answer is done. If a question does not make any sense, or is not factually coherent, explain why instead of answering something not correct. If you don't know the answer to a question, please don't share false information. CONTEXT: {context} Question: {question} Answer: """ if __name__ == "__main__": import lancedb parser = argparse.ArgumentParser(description="Query a vector DB") # Input parser.add_argument( "--question", help="The question that needs to be answered", default="what is flash attention?", ) # Input parser.add_argument( "--db_path", type=str, default="/tmp/lancedb", help="The path to read the vector DB", ) args = parser.parse_args() db = lancedb.connect(args.db_path) tbl = db.open_table("test") resp = tbl.search(args.question).limit(10).to_pandas() context = "\n".join(resp["text"].values) context = "\n".join(pd.Series(context.split("\n")).drop_duplicates()) prompt = TEMPLATE.format(context=context, question=args.question) model, tokenizer = load("mlx-community/NeuralBeagle14-7B-4bit-mlx") ans = generate(model, tokenizer, prompt=prompt, verbose=False, max_tokens=512) pprint(ans)
[ "lancedb.connect" ]
[((689, 745), 'argparse.ArgumentParser', 'argparse.ArgumentParser', ([], {'description': '"""Query a vector DB"""'}), "(description='Query a vector DB')\n", (712, 745), False, 'import argparse\n'), ((1112, 1141), 'lancedb.connect', 'lancedb.connect', (['args.db_path'], {}), '(args.db_path)\n', (1127, 1141), False, 'import lancedb\n'), ((1446, 1494), 'mlx_lm.load', 'load', (['"""mlx-community/NeuralBeagle14-7B-4bit-mlx"""'], {}), "('mlx-community/NeuralBeagle14-7B-4bit-mlx')\n", (1450, 1494), False, 'from mlx_lm import generate, load\n'), ((1505, 1577), 'mlx_lm.generate', 'generate', (['model', 'tokenizer'], {'prompt': 'prompt', 'verbose': '(False)', 'max_tokens': '(512)'}), '(model, tokenizer, prompt=prompt, verbose=False, max_tokens=512)\n', (1513, 1577), False, 'from mlx_lm import generate, load\n'), ((1583, 1594), 'pprint.pprint', 'pprint', (['ans'], {}), '(ans)\n', (1589, 1594), False, 'from pprint import pprint\n')]
import lancedb uri = "./.lancedb" db = lancedb.connect(uri) table = db.open_table("my_table") # table.delete("createAt = '1690358416394516300'") # 此条莫名失败了。Column createat does not exist in the dataset table.delete("item = 'foo'") df = table.to_pandas() print(df)
[ "lancedb.connect" ]
[((40, 60), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (55, 60), False, 'import lancedb\n')]
import requests import time import numpy as np import pyarrow as pa import lancedb import logging import os from tqdm import tqdm from pathlib import Path from transformers import AutoConfig logging.basicConfig(level=logging.INFO) logger = logging.getLogger(__name__) TEI_URL= os.getenv("EMBED_URL") + "/embed" DIRPATH = "/usr/src/docs_dir" TABLE_NAME = "docs" config = AutoConfig.from_pretrained(os.getenv("EMBED_MODEL")) EMB_DIM = config.hidden_size CREATE_INDEX = int(os.getenv("CREATE_INDEX")) BATCH_SIZE = int(os.getenv("BATCH_SIZE")) NUM_PARTITIONS = int(os.getenv("NUM_PARTITIONS")) NUM_SUB_VECTORS = int(os.getenv("NUM_SUB_VECTORS")) HEADERS = { "Content-Type": "application/json" } def embed_and_index(): files = Path(DIRPATH).rglob("*") texts = [] for file in files: if file.is_file(): try: text = file.open().read() if text: texts.append(text) except (OSError, UnicodeDecodeError) as e: logger.error("Error reading file: ", e) except Exception as e: logger.error("Unhandled exception: ", e) raise logger.info(f"Successfully read {len(texts)} files") db = lancedb.connect("/usr/src/.lancedb") schema = pa.schema( [ pa.field("vector", pa.list_(pa.float32(), EMB_DIM)), pa.field("text", pa.string()), ] ) tbl = db.create_table(TABLE_NAME, schema=schema, mode="overwrite") start = time.time() for i in tqdm(range(int(np.ceil(len(texts) / BATCH_SIZE)))): payload = { "inputs": texts[i * BATCH_SIZE:(i + 1) * BATCH_SIZE], "truncate": True } resp = requests.post(TEI_URL, json=payload, headers=HEADERS) if resp.status_code != 200: raise RuntimeError(resp.text) vectors = resp.json() data = [ {"vector": vec, "text": text} for vec, text in zip(vectors, texts[i * BATCH_SIZE:(i + 1) * BATCH_SIZE]) ] tbl.add(data=data) logger.info(f"Embedding and ingestion of {len(texts)} items took {time.time() - start}") # IVF-PQ indexing if CREATE_INDEX: tbl.create_index(num_partitions=NUM_PARTITIONS, num_sub_vectors=NUM_SUB_VECTORS) if __name__ == "__main__": embed_and_index()
[ "lancedb.connect" ]
[((194, 233), 'logging.basicConfig', 'logging.basicConfig', ([], {'level': 'logging.INFO'}), '(level=logging.INFO)\n', (213, 233), False, 'import logging\n'), ((243, 270), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (260, 270), False, 'import logging\n'), ((281, 303), 'os.getenv', 'os.getenv', (['"""EMBED_URL"""'], {}), "('EMBED_URL')\n", (290, 303), False, 'import os\n'), ((401, 425), 'os.getenv', 'os.getenv', (['"""EMBED_MODEL"""'], {}), "('EMBED_MODEL')\n", (410, 425), False, 'import os\n'), ((475, 500), 'os.getenv', 'os.getenv', (['"""CREATE_INDEX"""'], {}), "('CREATE_INDEX')\n", (484, 500), False, 'import os\n'), ((519, 542), 'os.getenv', 'os.getenv', (['"""BATCH_SIZE"""'], {}), "('BATCH_SIZE')\n", (528, 542), False, 'import os\n'), ((565, 592), 'os.getenv', 'os.getenv', (['"""NUM_PARTITIONS"""'], {}), "('NUM_PARTITIONS')\n", (574, 592), False, 'import os\n'), ((616, 644), 'os.getenv', 'os.getenv', (['"""NUM_SUB_VECTORS"""'], {}), "('NUM_SUB_VECTORS')\n", (625, 644), False, 'import os\n'), ((1244, 1280), 'lancedb.connect', 'lancedb.connect', (['"""/usr/src/.lancedb"""'], {}), "('/usr/src/.lancedb')\n", (1259, 1280), False, 'import lancedb\n'), ((1523, 1534), 'time.time', 'time.time', ([], {}), '()\n', (1532, 1534), False, 'import time\n'), ((1746, 1799), 'requests.post', 'requests.post', (['TEI_URL'], {'json': 'payload', 'headers': 'HEADERS'}), '(TEI_URL, json=payload, headers=HEADERS)\n', (1759, 1799), False, 'import requests\n'), ((737, 750), 'pathlib.Path', 'Path', (['DIRPATH'], {}), '(DIRPATH)\n', (741, 750), False, 'from pathlib import Path\n'), ((1409, 1420), 'pyarrow.string', 'pa.string', ([], {}), '()\n', (1418, 1420), True, 'import pyarrow as pa\n'), ((1355, 1367), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (1365, 1367), True, 'import pyarrow as pa\n'), ((2166, 2177), 'time.time', 'time.time', ([], {}), '()\n', (2175, 2177), False, 'import time\n')]
import lancedb from datasets import Dataset from homematch.config import DATA_DIR, TABLE_NAME from homematch.data.types import ImageData def datagen() -> list[ImageData]: dataset = Dataset.load_from_disk(DATA_DIR / "properties_dataset") # return Image instances return [ImageData(**batch) for batch in dataset] def main() -> None: uri = str(DATA_DIR) + "/.lancedb/" db = lancedb.connect(uri) table = db.create_table(TABLE_NAME, schema=ImageData, exist_ok=True) data = datagen() table.add(data) if __name__ == "__main__": main()
[ "lancedb.connect" ]
[((188, 243), 'datasets.Dataset.load_from_disk', 'Dataset.load_from_disk', (["(DATA_DIR / 'properties_dataset')"], {}), "(DATA_DIR / 'properties_dataset')\n", (210, 243), False, 'from datasets import Dataset\n'), ((397, 417), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (412, 417), False, 'import lancedb\n'), ((286, 304), 'homematch.data.types.ImageData', 'ImageData', ([], {}), '(**batch)\n', (295, 304), False, 'from homematch.data.types import ImageData\n')]
import openai import os import lancedb import pickle import requests from pathlib import Path from bs4 import BeautifulSoup import re from langchain.document_loaders import UnstructuredHTMLLoader from langchain.embeddings import OpenAIEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import LanceDB from langchain.llms import OpenAI from langchain.chains import RetrievalQA # Function to fetch and save a page as an HTML file def save_page(url, save_dir): response = requests.get(url) if response.status_code == 200: soup = BeautifulSoup(response.content, 'html.parser') title = soup.find('title').text filename = f"{title}.html" with open(os.path.join(save_dir, filename), 'w', encoding='utf-8') as file: file.write(str(soup)) def get_document_title(document): m = str(document.metadata["source"]) title = re.findall("(.*)\.html", m) print("PRINTING TITLES") print(title) if title[0] is not None: return(title[0]) return '' # if "OPENAI_API_KEY" not in os.environ: openai.api_key = "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" assert len(openai.Model.list()["data"]) > 0 print("fetching data") # Base URL of Wikivoyage base_url = "https://en.wikivoyage.org/wiki/" # List of page titles to download page_titles = ["London", "Paris", "New_York_City"] # Add more as needed # Directory to save the HTML files save_directory = "./wikivoyage_pages" # Create the save directory if it doesn't exist if not os.path.exists(save_directory): os.makedirs(save_directory) # Loop through the page titles and download the pages for title in page_titles: url = f"{base_url}{title}" save_page(url, save_directory) docs_path = Path("cities.pkl") docs = [] if not docs_path.exists(): for p in Path("./wikivoyage_pages").rglob("*.html"): if p.is_dir(): continue loader = UnstructuredHTMLLoader(p) raw_document = loader.load() m = {} m["title"] = get_document_title(raw_document[0]) raw_document[0].metadata = raw_document[0].metadata | m raw_document[0].metadata["source"] = str(raw_document[0].metadata["source"]) docs = docs + raw_document with docs_path.open("wb") as fh: pickle.dump(docs, fh) else: with docs_path.open("rb") as fh: docs = pickle.load(fh) #split text text_splitter = RecursiveCharacterTextSplitter( chunk_size=500, chunk_overlap=50, ) documents = text_splitter.split_documents(docs) embeddings = OpenAIEmbeddings(openai_api_key="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") db = lancedb.connect('/tmp/lancedb') table = db.create_table("city_docs", data=[ {"vector": embeddings.embed_query("Hello World"), "text": "Hello World"} ], mode="overwrite") print("generated embeddings!") docsearch = LanceDB.from_documents(documents[5:], embeddings, connection=table) qa = RetrievalQA.from_chain_type(llm=OpenAI(openai_api_key="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"), chain_type="stuff", retriever=docsearch.as_retriever()) query_file = open('query.pkl', 'wb') pickle.dump(qa, query_file) query_file.close() print("returning query object")
[ "lancedb.connect" ]
[((1848, 1866), 'pathlib.Path', 'Path', (['"""cities.pkl"""'], {}), "('cities.pkl')\n", (1852, 1866), False, 'from pathlib import Path\n'), ((2545, 2609), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': '(500)', 'chunk_overlap': '(50)'}), '(chunk_size=500, chunk_overlap=50)\n', (2575, 2609), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter\n'), ((2691, 2782), 'langchain.embeddings.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {'openai_api_key': '"""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"""'}), "(openai_api_key=\n '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')\n", (2707, 2782), False, 'from langchain.embeddings import OpenAIEmbeddings\n'), ((2786, 2817), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (2801, 2817), False, 'import lancedb\n'), ((3012, 3079), 'langchain.vectorstores.LanceDB.from_documents', 'LanceDB.from_documents', (['documents[5:]', 'embeddings'], {'connection': 'table'}), '(documents[5:], embeddings, connection=table)\n', (3034, 3079), False, 'from langchain.vectorstores import LanceDB\n'), ((3293, 3320), 'pickle.dump', 'pickle.dump', (['qa', 'query_file'], {}), '(qa, query_file)\n', (3304, 3320), False, 'import pickle\n'), ((548, 565), 'requests.get', 'requests.get', (['url'], {}), '(url)\n', (560, 565), False, 'import requests\n'), ((959, 987), 're.findall', 're.findall', (['"""(.*)\\\\.html"""', 'm'], {}), "('(.*)\\\\.html', m)\n", (969, 987), False, 'import re\n'), ((1616, 1646), 'os.path.exists', 'os.path.exists', (['save_directory'], {}), '(save_directory)\n', (1630, 1646), False, 'import os\n'), ((1653, 1680), 'os.makedirs', 'os.makedirs', (['save_directory'], {}), '(save_directory)\n', (1664, 1680), False, 'import os\n'), ((619, 665), 'bs4.BeautifulSoup', 'BeautifulSoup', (['response.content', '"""html.parser"""'], {}), "(response.content, 'html.parser')\n", (632, 665), False, 'from bs4 import BeautifulSoup\n'), ((2030, 2055), 'langchain.document_loaders.UnstructuredHTMLLoader', 'UnstructuredHTMLLoader', (['p'], {}), '(p)\n', (2052, 2055), False, 'from langchain.document_loaders import UnstructuredHTMLLoader\n'), ((2414, 2435), 'pickle.dump', 'pickle.dump', (['docs', 'fh'], {}), '(docs, fh)\n', (2425, 2435), False, 'import pickle\n'), ((2497, 2512), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (2508, 2512), False, 'import pickle\n'), ((3118, 3194), 'langchain.llms.OpenAI', 'OpenAI', ([], {'openai_api_key': '"""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"""'}), "(openai_api_key='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')\n", (3124, 3194), False, 'from langchain.llms import OpenAI\n'), ((1238, 1257), 'openai.Model.list', 'openai.Model.list', ([], {}), '()\n', (1255, 1257), False, 'import openai\n'), ((1922, 1948), 'pathlib.Path', 'Path', (['"""./wikivoyage_pages"""'], {}), "('./wikivoyage_pages')\n", (1926, 1948), False, 'from pathlib import Path\n'), ((762, 794), 'os.path.join', 'os.path.join', (['save_dir', 'filename'], {}), '(save_dir, filename)\n', (774, 794), False, 'import os\n')]
import queue import threading from dataclasses import dataclass import lancedb import pyarrow as pa import numpy as np import torch import torch.nn.functional as F from safetensors import safe_open from tqdm import tqdm from .app.schemas.task import TaskCompletion from .ops.object_detectors import YOLOV8TRTEngine from .ops.ocr import PaddlePaddleOCRV4TRTEngine from .ops.optical_flow_estimators import RAFT from .ops.video_decoders import VPFVideoDecoder from .ops.clip import ClipVisionEncoder, ClipVisionEncoderTRTEngine from .utils.cvt import rgb_to_hsv_nhwc_uint8 @dataclass class FrameQueueItem: type: str task_id: str video_path: str result_queue: queue.Queue frames: torch.Tensor | None = None frame_idx: int | None = None fps: float | None = None total_frames: int | None = None width: int | None = None height: int | None = None @dataclass class PostProcessQueueItem: type: str task_id: str video_path: str batch_idx: int shape: tuple[int, int] preds: torch.Tensor result_queue: queue.Queue class Saver: def __init__(self, output_path: str): self.output_path = output_path self.db = lancedb.connect(output_path) table_names = self.db.table_names() if "clip" in table_names: self.clip_table = self.db.open_table("clip") else: schema = pa.schema([ pa.field("video_id", pa.utf8()), pa.field("frame_idx", pa.int32()), pa.field("clip_feature", pa.list_(pa.float32(), list_size=768)), ]) self.clip_table = self.db.create_table("clip", schema=schema) if "optical_flow" in table_names: self.optical_flow_table = self.db.open_table("optical_flow") else: schema = pa.schema([ pa.field("video_id", pa.utf8()), pa.field("frame_idx", pa.int32()), pa.field("optical_flow_score", pa.float32()), ]) self.optical_flow_table = self.db.create_table("optical_flow", schema=schema) if "cut_scores" in table_names: self.cut_scores_table = self.db.open_table("cut_scores") else: schema = pa.schema([ pa.field("video_id", pa.utf8()), pa.field("fps", pa.float32()), pa.field("cut_scores", pa.list_(pa.float32())), ]) self.cut_scores_table = self.db.create_table("cut_scores", schema=schema) if "ocr" in table_names: self.ocr_table = self.db.open_table("ocr") else: schema = pa.schema([ pa.field("video_id", pa.utf8()), pa.field("frame_idx", pa.int32()), pa.field("ocr_score", pa.float32()), pa.field("boxes", pa.list_(pa.list_(pa.list_(pa.int32, list_size=2), list_size=4))), pa.field("scores", pa.list_(pa.float32())), ]) self.ocr_table = self.db.create_table("ocr", schema=schema) def put_clip_features(self, clip_features: torch.Tensor): ... def put_optical_flow(self, optical_flow: torch.Tensor): ... def put_cut_scores(self, cut_scores: torch.Tensor): ... def put_ocr_results(self, ocr_score: float, boxes, scores): ... def put_det_results(self): ... class Pipeline: def __init__( self, batch_size: int, device_id: int = 0, raft_model_path: str = "./weights/raft_things.safetensors", ocr_model_path: str = "./weights/pp-ocr-v4-det-fp16.engine", det_model_path: str = "./weights/yolov8m-fp16.engine", ): self.batch_size = batch_size self.device_id = device_id device_id = 0 self.device_str = f"cuda:{device_id}" self.device = torch.device(self.device_str) self.clip_encoder = ClipVisionEncoder( model_name="ViT-L/14", device=self.device, ) self.clip_encoder = ClipVisionEncoderTRTEngine( "./weights/clip_vit_l14-fp16.engine", self.device, ) state_dict = {} with safe_open(raft_model_path, framework="pt", device=self.device_str) as f: for key in f.keys(): state_dict[key] = f.get_tensor(key) raft = RAFT() raft.load_state_dict(state_dict) raft.eval() raft.to(self.device) self.raft = raft self.pp_ocr = PaddlePaddleOCRV4TRTEngine(ocr_model_path, self.device) self.yolo_v8 = YOLOV8TRTEngine(det_model_path, self.device) self.frame_queue: queue.Queue[FrameQueueItem | None] = queue.Queue(maxsize=64) self.post_process_queue: queue.Queue[PostProcessQueueItem | None] = queue.Queue(maxsize=64) self.process_thread = threading.Thread(target=self.process_thread_fn) self.post_process_thread = threading.Thread(target=self.post_process_thread_fn) def compute_cut_scores( self, frames: torch.Tensor, last_hsv_frame: torch.Tensor | None, last_hsv_frame_2fps: torch.Tensor | None, last_hsv_frame_8fps: torch.Tensor | None, start_2fps: float, start_8fps: float, stride_2fps: float, stride_8fps: float, ): hsv_frames = rgb_to_hsv_nhwc_uint8(frames) cur = start_2fps indices_2fps = [] while round(cur) < frames.shape[0]: indices_2fps.append(round(cur)) cur += stride_2fps start_2fps = cur - frames.shape[0] indices_2fps_tensor = torch.as_tensor(indices_2fps, dtype=torch.int64, device=frames.device) cur = start_8fps indices_8fps = [] while round(cur) < frames.shape[0]: indices_8fps.append(round(cur)) cur += stride_8fps start_8fps = cur - frames.shape[0] indices_8fps_tensor = torch.as_tensor(indices_8fps, dtype=torch.int64, device=frames.device) hsv_frames_2fps = hsv_frames[indices_2fps_tensor] hsv_frames_8fps = hsv_frames[indices_8fps_tensor] if last_hsv_frame is None: diff = (hsv_frames[:-1] - hsv_frames[1:]).abs().to(torch.float32) else: prev_hsv_frames = torch.cat([last_hsv_frame[None], hsv_frames[:-1]], dim=0) diff = (prev_hsv_frames - hsv_frames).abs().to(torch.float32) if hsv_frames_2fps.shape[0] > 0: if last_hsv_frame_2fps is None: diff_2fps = (hsv_frames_2fps[:-1] - hsv_frames_2fps[1:]).abs().to(torch.float32) else: prev_hsv_frames_2fps = torch.cat([ last_hsv_frame_2fps[None], hsv_frames_2fps[:-1] ], dim=0) diff_2fps = (prev_hsv_frames_2fps - hsv_frames_2fps).abs().to(torch.float32) if hsv_frames_8fps.shape[0] > 0: if last_hsv_frame_8fps is None: diff_8fps = (hsv_frames_8fps[:-1] - hsv_frames_8fps[1:]).abs().to(torch.float32) else: prev_hsv_frames_8fps = torch.cat([ last_hsv_frame_8fps[None], hsv_frames_8fps[:-1] ], dim=0) diff_8fps = (prev_hsv_frames_8fps - hsv_frames_8fps).abs().to(torch.float32) last_hsv_frame = hsv_frames[-1] cut_scores = diff.flatten(1, 2).mean(dim=1) if hsv_frames_2fps.shape[0] > 0: cut_scores_2fps = diff_2fps.flatten(1, 2).mean(dim=1) last_hsv_frame_2fps = hsv_frames_2fps[-1] else: cut_scores_2fps = [] if hsv_frames_8fps.shape[0] > 0: cut_scores_8fps = diff_8fps.flatten(1, 2).mean(dim=1) last_hsv_frame_8fps = hsv_frames_8fps[-1] else: cut_scores_8fps = [] return ( cut_scores, cut_scores_2fps, cut_scores_8fps, last_hsv_frame, last_hsv_frame_2fps, last_hsv_frame_8fps, start_2fps, start_8fps, indices_2fps_tensor, indices_2fps, indices_8fps, ) def apply_resize(self, images: torch.Tensor, size: int) -> torch.Tensor: height, width = images.shape[-2:] if height < width: resize_to = (size, round(width * size / height)) else: resize_to = (round(height * size / width), size) return F.interpolate(images, size=resize_to, mode="bicubic") def apply_center_crop(self, images: torch.Tensor, factor: int = 32) -> torch.Tensor: height, width = images.shape[-2:] new_height = height // factor * factor new_width = width // factor * factor if new_height != height or new_width != width: start_h = (height - new_height) // 2 end_h = start_h + new_height start_w = (width - new_width) // 2 end_w = start_w + new_width images = images[..., start_h:end_h, start_w:end_w] return images @torch.no_grad() def process_thread_fn(self): while True: try: item = self.frame_queue.get(timeout=1) if item is None: break except queue.Empty: continue try: if item.type == "start": task_id = item.task_id video_path = item.video_path fps = item.fps stride_2fps = fps / 2.0 stride_8fps = fps / 8.0 frames_2fps_det_list = [] total_frames_2fps = 0 last_hsv_frame = None last_hsv_frame_2fps = None last_hsv_frame_8fps = None start_2fps = 0 start_8fps = 0 last_frame_2fps = None batch_idx_det = 0 batch_idx_flow = 0 results = [] elif item.type == "frames": frames = item.frames result_queue = item.result_queue ( cut_scores, cut_scores_2fps, cut_scores_8fps, last_hsv_frame, last_hsv_frame_2fps, last_hsv_frame_8fps, start_2fps, start_8fps, indices_2fps_tensor, indices_2fps, indices_8fps, ) = self.compute_cut_scores( frames, last_hsv_frame, last_hsv_frame_2fps, last_hsv_frame_8fps, start_2fps, start_8fps, stride_2fps, stride_8fps, ) results.append({ "type": "cut_scores", "task_id": task_id, "video_path": video_path, "frame_idx": item.frame_idx, "cut_scores": cut_scores, "cut_scores_2fps": cut_scores_2fps, "cut_scores_8fps": cut_scores_8fps, "indices_2fps": indices_2fps, "indices_8fps": indices_8fps, }) # -> b, 3, h, w frames = frames.permute(0, 3, 1, 2).float() frames.div_(255.0) frames.clamp_(0.0, 1.0) frames_2fps = frames[indices_2fps_tensor] if frames_2fps.shape[0] > 0: frames_2fps_resized_clip = self.apply_resize(frames_2fps, self.clip_encoder.input_res) height, width = frames.shape[-2:] frames_2fps_resized_det = self.apply_resize(frames_2fps, min(height, width) // 2) # clip clip_features = self.clip_encoder.encode(frames_2fps_resized_clip) clip_features = clip_features results.append({ "type": "clip", "task_id": task_id, "video_path": video_path, "frame_idx": item.frame_idx, "clip_features": clip_features, }) # center crop for det frames_2fps_det = self.apply_center_crop(frames_2fps_resized_det, factor=32) frames_2fps_det_list.append(frames_2fps_det) total_frames_2fps += frames_2fps_det.shape[0] # optical flow if total_frames_2fps >= 64: frames_2fps_det = torch.cat(frames_2fps_det_list, dim=0) total_frames = frames_2fps_det.shape[0] pp_ocr_preds = self.pp_ocr.detect(frames_2fps_det) self.post_process_queue.put( PostProcessQueueItem( type="pp_orc", task_id=task_id, video_path=video_path, batch_idx=batch_idx_det, shape=tuple(frames_2fps_det.shape[-2:]), preds=pp_ocr_preds, result_queue=result_queue, ) ) yolo_v8_preds = self.yolo_v8.detect(frames_2fps_det) self.post_process_queue.put( PostProcessQueueItem( type="yolo_v8", task_id=task_id, video_path=video_path, batch_idx=batch_idx_det, shape=tuple(frames_2fps_det.shape[-2:]), preds=yolo_v8_preds, result_queue=result_queue, ) ) batch_idx_det += 1 if last_frame_2fps is not None: frames_2fps_det = torch.cat([last_frame_2fps[None], frames_2fps_det], dim=0) offset = 1 else: offset = 0 frames_2fps_flow = frames_2fps_det * 2 - 1 batch_size = 32 for i in range(0 + offset, total_frames + offset, batch_size): if i + batch_size > total_frames + offset: break start = max(i - 1, 0) end = min(i + batch_size, total_frames) frames1 = frames_2fps_flow[start:end - 1] frames2 = frames_2fps_flow[start + 1:end] flows = self.raft(frames1, frames2, update_iters=12) mag = torch.sqrt(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2) optical_flow_scores = mag.flatten(1).mean(dim=1) results.append({ "type": "optical_flow", "task_id": task_id, "video_path": video_path, "batch_idx": batch_idx_flow, "optical_flow_scores": optical_flow_scores, }) batch_idx_flow += 1 last_frame_2fps = frames_2fps_det[-1] frames_2fps_det_list = [frames_2fps_det[i:]] total_frames_2fps = frames_2fps_det_list[-1].shape[0] elif item.type == "end": # optical flow if total_frames_2fps > 0: frames_2fps_det = torch.cat(frames_2fps_det_list, dim=0) total_frames = frames_2fps_det.shape[0] pp_ocr_preds = self.pp_ocr.detect(frames_2fps_det) self.post_process_queue.put( PostProcessQueueItem( type="pp_orc", task_id=task_id, video_path=video_path, batch_idx=batch_idx_det, shape=tuple(frames_2fps_det.shape[-2:]), preds=pp_ocr_preds, result_queue=result_queue, ) ) yolo_v8_preds = self.yolo_v8.detect(frames_2fps_det) self.post_process_queue.put( PostProcessQueueItem( type="yolo_v8", task_id=task_id, video_path=video_path, batch_idx=batch_idx_det, shape=tuple(frames_2fps_det.shape[-2:]), preds=yolo_v8_preds, result_queue=result_queue, ) ) batch_idx_det += 1 if last_frame_2fps is not None: frames_2fps_det = torch.cat([last_frame_2fps[None], frames_2fps_det], dim=0) offset = 1 else: offset = 0 frames_2fps_flow = frames_2fps_det * 2 - 1 batch_size = 32 if frames_2fps_det.shape[0] > 1: for i in range(0 + offset, total_frames + offset, batch_size): start = max(i - 1, 0) end = min(i + batch_size, total_frames) frames1 = frames_2fps_flow[start:end - 1] frames2 = frames_2fps_flow[start + 1:end] if frames1.shape[0] > 0 and frames2.shape[0] > 0: flows = self.raft(frames1, frames2, update_iters=12) mag = torch.sqrt(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2) optical_flow_scores = mag.flatten(1).mean(dim=1) results.append({ "type": "optical_flow", "task_id": task_id, "video_path": video_path, "batch_idx": batch_idx_flow, "optical_flow_scores": optical_flow_scores, }) batch_idx_flow += 1 last_frame_2fps = None frames_2fps_det_list = [] total_frames_2fps = 0 for res in results: new_res = {} for key, val in res.items(): if isinstance(val, torch.Tensor): new_res[key] = val.cpu().tolist() else: new_res[key] = val result_queue.put(new_res) torch.cuda.empty_cache() item.result_queue.put( TaskCompletion( id=task_id, status="completed", fps=item.fps, total_frames=item.total_frames, width=item.width, height=item.height, ) ) else: raise ValueError(f"unknown item type: {item.type}") except Exception as e: import io import traceback str_io = io.StringIO() traceback.print_exc(file=str_io) item.result_queue.put( TaskCompletion( id=task_id, status="failed", message=str_io.getvalue() + f"\nitem: {item}" + f"\n{frames_2fps_det.shape}", ) ) print("process_thread_fn stopped.") def post_process_thread_fn(self): while True: try: item = self.post_process_queue.get(timeout=1) if item is None: break except queue.Empty: continue if item.type == "yolo_v8": results = self.yolo_v8.post_process(item.preds.cpu().numpy()) item.result_queue.put({ "type": "det", "detector": "yolo_v8", "task_id": item.task_id, "batch_idx": item.batch_idx, "shape": item.shape, "results": results, }) elif item.type == "pp_orc": boxes, scores, ocr_scores = self.pp_ocr.post_process(item.preds.cpu().numpy()) item.result_queue.put({ "type": "ocr", "detector": "pp_orc", "task_id": item.task_id, "batch_idx": item.batch_idx, "shape": item.shape, "boxes": boxes, "scores": scores, "ocr_scores": ocr_scores, }) else: raise ValueError(f"unknown item type: {item.type}") print("post_process_thread_fn stopped.") def start(self): self.process_thread.start() self.post_process_thread.start() def close(self): self.frame_queue.put(None) self.post_process_queue.put(None) self.process_thread.join() self.post_process_thread.join() @torch.no_grad() def __call__( self, task_id: str, video_path: str, result_queue: queue.Queue, verbose: bool = False, ): print("video_path", video_path) decoder = VPFVideoDecoder( video_path=video_path, batch_size=self.batch_size, device_id=self.device_id, ) if decoder.width != 1280 or decoder.height != 720: result_queue.put( TaskCompletion( id=task_id, status="failed", message=( "video resolution is not 720x1280 " f"({decoder.height}x{decoder.width})." ), ) ) return self.frame_queue.put( FrameQueueItem( type="start", task_id=task_id, video_path=video_path, fps=decoder.fps, result_queue=result_queue, ), ) frame_idx = 0 for frames in tqdm(decoder.iter_frames(pixel_format="rgb"), disable=not verbose): self.frame_queue.put( FrameQueueItem( type="frames", task_id=task_id, video_path=video_path, frames=frames, frame_idx=frame_idx, result_queue=result_queue, ), ) frame_idx += frames.shape[0] self.frame_queue.put( FrameQueueItem( type="end", task_id=task_id, video_path=video_path, fps=decoder.fps, total_frames=decoder.total_frames, width=decoder.width, height=decoder.height, result_queue=result_queue, ) )
[ "lancedb.connect" ]
[((8969, 8984), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (8982, 8984), False, 'import torch\n'), ((22228, 22243), 'torch.no_grad', 'torch.no_grad', ([], {}), '()\n', (22241, 22243), False, 'import torch\n'), ((1191, 1219), 'lancedb.connect', 'lancedb.connect', (['output_path'], {}), '(output_path)\n', (1206, 1219), False, 'import lancedb\n'), ((3869, 3898), 'torch.device', 'torch.device', (['self.device_str'], {}), '(self.device_str)\n', (3881, 3898), False, 'import torch\n'), ((4711, 4734), 'queue.Queue', 'queue.Queue', ([], {'maxsize': '(64)'}), '(maxsize=64)\n', (4722, 4734), False, 'import queue\n'), ((4811, 4834), 'queue.Queue', 'queue.Queue', ([], {'maxsize': '(64)'}), '(maxsize=64)\n', (4822, 4834), False, 'import queue\n'), ((4866, 4913), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.process_thread_fn'}), '(target=self.process_thread_fn)\n', (4882, 4913), False, 'import threading\n'), ((4949, 5001), 'threading.Thread', 'threading.Thread', ([], {'target': 'self.post_process_thread_fn'}), '(target=self.post_process_thread_fn)\n', (4965, 5001), False, 'import threading\n'), ((5632, 5702), 'torch.as_tensor', 'torch.as_tensor', (['indices_2fps'], {'dtype': 'torch.int64', 'device': 'frames.device'}), '(indices_2fps, dtype=torch.int64, device=frames.device)\n', (5647, 5702), False, 'import torch\n'), ((5947, 6017), 'torch.as_tensor', 'torch.as_tensor', (['indices_8fps'], {'dtype': 'torch.int64', 'device': 'frames.device'}), '(indices_8fps, dtype=torch.int64, device=frames.device)\n', (5962, 6017), False, 'import torch\n'), ((8366, 8419), 'torch.nn.functional.interpolate', 'F.interpolate', (['images'], {'size': 'resize_to', 'mode': '"""bicubic"""'}), "(images, size=resize_to, mode='bicubic')\n", (8379, 8419), True, 'import torch.nn.functional as F\n'), ((4204, 4270), 'safetensors.safe_open', 'safe_open', (['raft_model_path'], {'framework': '"""pt"""', 'device': 'self.device_str'}), "(raft_model_path, framework='pt', device=self.device_str)\n", (4213, 4270), False, 'from safetensors import safe_open\n'), ((6293, 6350), 'torch.cat', 'torch.cat', (['[last_hsv_frame[None], hsv_frames[:-1]]'], {'dim': '(0)'}), '([last_hsv_frame[None], hsv_frames[:-1]], dim=0)\n', (6302, 6350), False, 'import torch\n'), ((6665, 6732), 'torch.cat', 'torch.cat', (['[last_hsv_frame_2fps[None], hsv_frames_2fps[:-1]]'], {'dim': '(0)'}), '([last_hsv_frame_2fps[None], hsv_frames_2fps[:-1]], dim=0)\n', (6674, 6732), False, 'import torch\n'), ((7104, 7171), 'torch.cat', 'torch.cat', (['[last_hsv_frame_8fps[None], hsv_frames_8fps[:-1]]'], {'dim': '(0)'}), '([last_hsv_frame_8fps[None], hsv_frames_8fps[:-1]], dim=0)\n', (7113, 7171), False, 'import torch\n'), ((20200, 20213), 'io.StringIO', 'io.StringIO', ([], {}), '()\n', (20211, 20213), False, 'import io\n'), ((20230, 20262), 'traceback.print_exc', 'traceback.print_exc', ([], {'file': 'str_io'}), '(file=str_io)\n', (20249, 20262), False, 'import traceback\n'), ((1441, 1450), 'pyarrow.utf8', 'pa.utf8', ([], {}), '()\n', (1448, 1450), True, 'import pyarrow as pa\n'), ((1491, 1501), 'pyarrow.int32', 'pa.int32', ([], {}), '()\n', (1499, 1501), True, 'import pyarrow as pa\n'), ((1874, 1883), 'pyarrow.utf8', 'pa.utf8', ([], {}), '()\n', (1881, 1883), True, 'import pyarrow as pa\n'), ((1924, 1934), 'pyarrow.int32', 'pa.int32', ([], {}), '()\n', (1932, 1934), True, 'import pyarrow as pa\n'), ((1984, 1996), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (1994, 1996), True, 'import pyarrow as pa\n'), ((2298, 2307), 'pyarrow.utf8', 'pa.utf8', ([], {}), '()\n', (2305, 2307), True, 'import pyarrow as pa\n'), ((2342, 2354), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (2352, 2354), True, 'import pyarrow as pa\n'), ((2695, 2704), 'pyarrow.utf8', 'pa.utf8', ([], {}), '()\n', (2702, 2704), True, 'import pyarrow as pa\n'), ((2745, 2755), 'pyarrow.int32', 'pa.int32', ([], {}), '()\n', (2753, 2755), True, 'import pyarrow as pa\n'), ((2796, 2808), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (2806, 2808), True, 'import pyarrow as pa\n'), ((1554, 1566), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (1564, 1566), True, 'import pyarrow as pa\n'), ((2405, 2417), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (2415, 2417), True, 'import pyarrow as pa\n'), ((2956, 2968), 'pyarrow.float32', 'pa.float32', ([], {}), '()\n', (2966, 2968), True, 'import pyarrow as pa\n'), ((12642, 12680), 'torch.cat', 'torch.cat', (['frames_2fps_det_list'], {'dim': '(0)'}), '(frames_2fps_det_list, dim=0)\n', (12651, 12680), False, 'import torch\n'), ((19547, 19571), 'torch.cuda.empty_cache', 'torch.cuda.empty_cache', ([], {}), '()\n', (19569, 19571), False, 'import torch\n'), ((2863, 2894), 'pyarrow.list_', 'pa.list_', (['pa.int32'], {'list_size': '(2)'}), '(pa.int32, list_size=2)\n', (2871, 2894), True, 'import pyarrow as pa\n'), ((14150, 14208), 'torch.cat', 'torch.cat', (['[last_frame_2fps[None], frames_2fps_det]'], {'dim': '(0)'}), '([last_frame_2fps[None], frames_2fps_det], dim=0)\n', (14159, 14208), False, 'import torch\n'), ((14998, 15055), 'torch.sqrt', 'torch.sqrt', (['(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2)'], {}), '(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2)\n', (15008, 15055), False, 'import torch\n'), ((15935, 15973), 'torch.cat', 'torch.cat', (['frames_2fps_det_list'], {'dim': '(0)'}), '(frames_2fps_det_list, dim=0)\n', (15944, 15973), False, 'import torch\n'), ((17443, 17501), 'torch.cat', 'torch.cat', (['[last_frame_2fps[None], frames_2fps_det]'], {'dim': '(0)'}), '([last_frame_2fps[None], frames_2fps_det], dim=0)\n', (17452, 17501), False, 'import torch\n'), ((18356, 18413), 'torch.sqrt', 'torch.sqrt', (['(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2)'], {}), '(flows[:, 0, ...] ** 2 + flows[:, 1, ...] ** 2)\n', (18366, 18413), False, 'import torch\n')]
import os import openai import json import numpy as np from numpy.linalg import norm import re from time import time, sleep from uuid import uuid4 import datetime import lancedb import pandas as pd def open_file(filepath): with open(filepath, 'r', encoding='utf-8') as infile: return infile.read() def save_file(filepath, content): with open(filepath, 'w', encoding='utf-8') as outfile: outfile.write(content) def timestamp_to_datetime(unix_time): return datetime.datetime.fromtimestamp(unix_time).strftime("%A, %B %d, %Y at %I:%M%p %Z") def gpt3_embedding(content, engine='text-embedding-ada-002'): content = content.encode(encoding='ASCII', errors='ignore').decode() response = openai.Embedding.create(input=content, engine=engine) vector = response['data'][0]['embedding'] return vector def ai_completion(prompt, engine='gpt-3.5-turbo', temp=0.0, top_p=1.0, tokens=400, freq_pen=0.0, pres_pen=0.0, stop=['USER:', 'RAVEN:']): max_retry = 5 retry = 0 prompt = prompt.encode(encoding='ASCII',errors='ignore' ).decode() while True: try: response = openai.Completion.createChatCompletion( model=engine, prompt=prompt, temperature=temp, max_tokens=tokens, top_p=top_p, frequency_penalty=freq_pen, presence_penalty=pres_pen, stop=stop) text = response[ 'choices' ][0][ 'text' ].strip() text = re.sub( '[\r\n]+', '\n', text ) text = re.sub( '[\t ]+', ' ', text ) filename = '%s_gpt3.txt' % time() if not os.path.exists( 'gpt3_logs' ): os.makedirs( 'gpt3_logs' ) save_file( 'gpt3_logs/%s' % filename, prompt + '\n\n==========\n\n' + text ) return text except Exception as oops: retry += 1 if retry >= max_retry: return "GPT3 error: %s" % oops print( 'Error communicating with OpenAI:', oops ) sleep(1) initialization_data = { 'unique_id': '2c9a93d5-3631-4faa-8eac-a99b92e45d50', 'vector': [-0.07254597, -0.00345811, 0.038447 , 0.025837 , -0.01153462, 0.05443505, 0.04415885, -0.03636164, 0.04025393, 0.07552634, 0.05359982, 0.00822271, -0.01921194, 0.09719925, -0.05354664, 0.06897003, 0.01113722, 0.06425729, 0.04223888, -0.05898998, -0.01620383, 0.01389384, 0.02873985, -0.00392985, -0.02874645, 0.02680893, -0.01051578, -0.0792539 , -0.03293172, -0.00302758, -0.03745122, -0.02573149, -0.00473748, -0.04199643, -0.03275133, 0.00779039, 0.00624639, 0.06108246, -0.03870484, 0.06269313, -0.06609031, -0.01554973, -0.04453023, -0.00073963, 0.01021871, -0.02984073, 0.00474442, 0.00195324, -0.02518238, -0.00426692, 0.00750736, 0.10541135, 0.08878568, 0.05580394, -0.01232905, -0.04016594, 0.04829635, -0.05689557, -0.01863352, 0.03308525, 0.06468356, -0.03367596, 0.03575945, -0.02212196, -0.01714826, -0.00585904, -0.09612011, -0.00102483, 0.06920582, 0.05855923, -0.04266937, -0.03763324, -0.02187943, -0.00141346, -0.086646 , 0.02106668, 0.00786448, 0.04093482, -0.00187637, 0.02952651, -0.03702659, -0.02844533, 0.00322303, -0.02380866, -0.05954637, 0.07149482, -0.0065098 , 0.06807149, -0.00099369, 0.05040864, 0.04761266, 0.01862198, -0.05431763, 0.00940712, -0.00970824, -0.02216387, 0.024306 , 0.03772607, -0.01540066, 0.03771403, 0.01400787, -0.09354229, -0.06321603, -0.09549774, 0.00895245, -0.01175102, 0.03934404, 0.00956635, -0.04152715, 0.04295438, 0.02825363, 0.02063269, 0.02212336, -0.06888197, 0.01428573, 0.04887657, 0.00304061, 0.03196091, 0.03902192, 0.02360773, -0.02807535, 0.01558309, 0.02165642, 0.01129555, 0.0567826 , -0.00659211, -0.01081236, 0.01809447, 0.00318123, -0.01214105, -0.05691559, -0.01717793, 0.05293235, 0.01663713, 0.04678147, -0.02094 , -0.05482098, 0.05463412, 0.00163532, 0.00956752, -0.03624124, -0.02359207, 0.01571903, -0.01502842, 0.03324307, 0.01896691, 0.02235259, 0.02551061, -0.02953271, 0.05505196, -0.03115846, -0.01975026, -0.05484571, -0.01757487, -0.01038232, -0.06098176, -0.01663185, -0.06602633, -0.00643233, 0.00167366, -0.04243006, 0.01024193, -0.02288529, -0.06190364, 0.03787598, 0.03914008, -0.04915332, 0.0182827 , 0.0136188 , 0.02917461, 0.03118066, -0.03110682, -0.04193405, -0.01370175, -0.03901035, 0.00850587, 0.01056607, -0.00084098, -0.01737773, 0.00836137, 0.01500763, 0.00917414, -0.07946376, 0.02008886, 0.04600394, 0.01271509, -0.01654603, -0.04405601, 0.01442427, 0.00967625, 0.01212494, 0.01189141, 0.03507042, -0.00291006, 0.04226362, -0.0958102 , 0.04722575, -0.02520623, -0.00780957, -0.01983704, -0.02350736, -0.03137485, 0.00325953, 0.10679087, -0.08251372, 0.02922777, -0.05723861, -0.05683867, -0.04093323, -0.04769454, -0.02704669, -0.04450696, 0.03854201, 0.05599346, -0.07225747, -0.01060745, -0.01285277, -0.02004824, 0.00567907, -0.01130959, 0.03845671, -0.06483931, -0.00013804, 0.00342195, -0.00497795, 0.03194252, 0.06014316, 0.07774884, -0.02778566, -0.06470748, 0.02103901, 0.02202238, 0.02044025, 0.10802107, 0.00356093, -0.01817842, 0.09661267, -0.05937773, -0.08208849, -0.05190327, -0.0302214 , 0.05572621, -0.06395542, -0.03078226, 0.00083952, 0.09572925, -0.04516173, -0.0123177 , 0.09613901, -0.05666108, -0.00537586, 0.04220096, 0.00019196, 0.00295547, -0.07350546, -0.00707971, -0.01553643, -0.05214835, 0.00311794, 0.00742682, -0.02943217, 0.06675503, 0.04113274, -0.0809793 , 0.03398148, 0.01721729, 0.03014007, -0.04178908, 0.01025263, 0.03336379, 0.05700357, 0.10388609, 0.00663307, -0.05146715, -0.02173147, -0.02297893, -0.01923811, 0.03292958, 0.0521661 , 0.03923552, 0.01330443, 0.02524009, 0.06507587, -0.01531762, -0.04601574, 0.0499142 , 0.06374968, 0.06080135, -0.08060206, 0.03382473, -0.03596291, -0.06714796, -0.08815136, 0.02092835, 0.10282409, 0.07779143, -0.01839681, -0.03541641, 0.00666599, 0.0029895 , -0.08307225, -0.06535257, 0.01114002, -0.06142527, -0.01779631, 0.04441926, 0.02008377, 0.03211711, -0.02073815, -0.01346437, 0.02578364, -0.01888524, 0.03310522, -0.02017466, 0.0198052 , -0.01019527, -0.02200533, -0.02650121, -0.02987311, -0.04946938, -0.05915657, -0.0779579 , 0.03368903, 0.01859711, 0.02692219, 0.04209578, -0.01279042, -0.00151735, -0.03290961, 0.00719433, -0.05409581, 0.04818217, -0.00339916, 0.01444317, -0.04898094, -0.02065373, -0.04324449, -0.01409152, -0.02882394, 0.0129813 , -0.03886433, -0.08824961, 0.02457459, -0.03383131, 0.04405662, 0.03947931, 0.02983763, 0.00124698, 0.01098392, 0.05948395, 0.08565806, 0.02848131, -0.00725272, -0.04415287, -0.03293212, -0.01364554, -0.09744117, -0.05662472, 0.03124948, -0.04624591, -0.00605065, -0.06229377, 0.08636316, -0.03645795, 0.08642905, 0.03093746, -0.08031843, 0.01407037, 0.09892832, 0.03219265, 0.02964027, -0.00517425, -0.03442131, -0.01141241, -0.06644958, -0.07285954, 0.00890575, -0.01360151, 0.00057073, -0.08988309, 0.00797763, 0.0176619 , 0.00745209, -0.07096376, 0.07894821, -0.08301938, 0.0990236 , 0.03789177, -0.01905026, 0.0547296 , -0.06224509, 0.01964617, 0.08179896, -0.0852924 , 0.00475453, -0.01451678, 0.03582037, -0.04732088, -0.041508 , 0.05553002, -0.00753875, -0.02849884, 0.04659286, -0.05146529, -0.0661836 , -0.00761966, 0.01581906, 0.02444271, -0.01438573, -0.03466942, -0.06876651, -0.02311521, -0.00312491, 0.03457906, -0.04614082, 0.03010868, 0.0206049 , 0.08378315, -0.03001363, -0.00827654, 0.01580172, -0.04855691, 0.00014473, -0.01702366, 0.06371997, 0.00924862, -0.01441237, 0.0184262 , 0.03586025, 0.07453281, -0.01822053, 0.00263505, -0.07093351, -0.02956585, 0.0937797 , -0.03792839, 0.03657963, -0.01717029, 0.0077794 , 0.06886019, 0.04470135, 0.04228634, 0.06212147, -0.05456647, -0.02041842, 0.02251387, 0.06653161, -0.00503211, 0.03463385, -0.02718318, 0.00118317, -0.02953942, -0.04361469, 0.01001209, 0.01472133, -0.07398187, 0.00152049, -0.02058817, -0.03011479, -0.03247686, -0.03999605, 0.00089937, 0.06058171, -0.1016895 , 0.07500667, 0.03293885, -0.05828201, -0.01353116, 0.06867946, -0.03266895, -0.02314214, 0.03284731, 0.02857622, 0.05733896, 0.05395727, 0.06677917, -0.01256167, 0.01832761, 0.01509516, 0.08785269, -0.01094873, -0.09930896, -0.00904166, 0.01920987, 0.01392063, -0.03855692, 0.04157091, -0.05284394, 0.01217607, -0.00495155, -0.02351189, 0.03753581, 0.03075539, 0.0635642 , 0.05873286, 0.00987345, 0.05255824, -0.08698288, 0.10400596, -0.00647114, -0.00831464, 0.0055213 , 0.01613558, -0.10711982, 0.00563591, 0.03591603, 0.00221161, -0.01541905, -0.0879847 , -0.05289326, -0.04107964, -0.04039652], 'speaker': 'USER', 'time': 1695146425.0193892, 'message': 'this is a test.', 'timestring': 'Tuesday, September 19, 2023 at 02:00PM ' } import pyarrow as pa class LanceTable: def __init__(self): # Initialize lancedb self.db = lancedb.connect( "/tmp/fresh-lancedb" ) # self.schema = pa.schema([ # pa.field("unique_id", pa.string()), # pa.field("vector", pa.list_(pa.float32())), # pa.field("speaker", pa.string()), # pa.field("time", pa.float64()), # pa.field("message", pa.string()), # pa.field("timestring", pa.string()), # ]) # Create the table with the defined schema panda_data_frame = pd.DataFrame([ initialization_data ]) table_name = "lance-table" if table_name in self.db.table_names(): print( "table %s already exists" % table_name ) self.db.drop_table(table_name) # Drop the table if it already exists self.table = self.db.create_table( table_name, panda_data_frame ) else: print( "creating table: %s" % table_name ) self.table = self.db.create_table( table_name, panda_data_frame ) # Insert the provided data into the table # self.table_initialized = False # self.table = None print(json.dumps(initialization_data, indent=4)) # Ensure 'embedded_user_input' is a numpy array # embedded_user_input = np.array(initialization_data['vector']) # # Flatten the array # flattened_input = embedded_user_input.flatten().tolist() # initialization_data[ "vector" ] = flattened_input # dataframe = pd.DataFrame([ initialization_data ]) # arrow_table = pa.Table.from_pandas(dataframe, panda_data_frame) # self.table.add( arrow_table ) # self.table.add( dataframe ) def add(self, unique_id_arg, embedded_message, speaker, timestamp, message, timestring ): # Ensure 'embedded_user_input' is a numpy array # embedded_user_input = np.array( embedded_message ) # Flatten the array # flattened_input = embedded_user_input.flatten().tolist() # embedded_user_input = flattened_input # embedded_user_input = np.array(embedded_message['vector']) # Flatten the array # flattened_input = embedded_user_input.flatten().tolist() # embedded_message[ "vector" ] = flattened_input data = { "unique_id": unique_id_arg, "vector": embedded_message, "speaker": speaker, "time": timestamp, "message": message, "timestring": timestring } # print( data ) dataframe = pd.DataFrame([ data ]) # arrow_table = pa.Table.from_pandas(dataframe, panda_data_frame ) # self.table.add( arrow_table ) self.table.add( dataframe ) lanceTable = LanceTable() import tensorflow_hub as hub # Load the Universal Sentence Encoder encoder = hub.load('https://tfhub.dev/google/universal-sentence-encoder/4') if __name__ == '__main__': openai.api_key = open_file('/home/adamsl/linuxBash/pinecone_chat_dave_s/key_openai.txt') while True: # user_input = input('\n\nUSER: ') user_input = "hi" timestamp = time() timestring = timestamp_to_datetime(timestamp) unique_id = str(uuid4()) # embedded_user_input = encoder([ user_input ]).numpy() # Convert the text into vector form # embedded_user_input = gpt3_embedding( user_input ) embedded_user_input = lanceTable.table.embedding_functions[ 'vector' ].function.compute_query_embeddings( user_input )[ 0 ] speaker = 'USER' message = user_input # embedded_user_input = np.array( embedded_user_input ) # flattened_input = [float(item) for item in embedded_user_input.flatten().tolist()] # Insert User's input to lancedb lanceTable.add( unique_id, embedded_user_input, speaker, timestamp, message, timestring ) query_builder = lanceTable.LanceVectorQueryBuilder( lanceTable.table, embedded_user_input, 'vector' ) # Search for relevant message unique ids in lancedb # results = lanceTable.table.search( embedded_user_input ).limit( 30 ).to_df() results = query_builder.to_arrow() dataframe = results.to_pandas() print ( dataframe ) chance_to_quit = input( "Press q to quit: " ) if chance_to_quit == "q": break break # print ( results ) # conversation = "\n".join(results['message'].tolist()) # prompt = open_file('prompt_response.txt').replace('<<CONVERSATION>>', conversation).replace('<<MESSAGE>>', user_input) # ai_completion_text = ai_completion(prompt) # timestamp = time() # timestring = timestamp_to_datetime(timestamp) # embedded_ai_completion = gpt3_embedding(ai_completion_text) # unique_id = str(uuid4()) # speaker = 'RAVEN' # thetimestamp = timestamp # message = ai_completion_text # timestring = timestring # Insert AI's response to lancedb # lanceTable.table.add([( unique_id, embedded_ai_completion, speaker, timestamp, timestring )]) # print('\n\nRAVEN: %s' % ai_completion_text)
[ "lancedb.connect" ]
[((12752, 12817), 'tensorflow_hub.load', 'hub.load', (['"""https://tfhub.dev/google/universal-sentence-encoder/4"""'], {}), "('https://tfhub.dev/google/universal-sentence-encoder/4')\n", (12760, 12817), True, 'import tensorflow_hub as hub\n'), ((720, 773), 'openai.Embedding.create', 'openai.Embedding.create', ([], {'input': 'content', 'engine': 'engine'}), '(input=content, engine=engine)\n', (743, 773), False, 'import openai\n'), ((9917, 9954), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/fresh-lancedb"""'], {}), "('/tmp/fresh-lancedb')\n", (9932, 9954), False, 'import lancedb\n'), ((10396, 10431), 'pandas.DataFrame', 'pd.DataFrame', (['[initialization_data]'], {}), '([initialization_data])\n', (10408, 10431), True, 'import pandas as pd\n'), ((12464, 12484), 'pandas.DataFrame', 'pd.DataFrame', (['[data]'], {}), '([data])\n', (12476, 12484), True, 'import pandas as pd\n'), ((13049, 13055), 'time.time', 'time', ([], {}), '()\n', (13053, 13055), False, 'from time import time, sleep\n'), ((486, 528), 'datetime.datetime.fromtimestamp', 'datetime.datetime.fromtimestamp', (['unix_time'], {}), '(unix_time)\n', (517, 528), False, 'import datetime\n'), ((1132, 1324), 'openai.Completion.createChatCompletion', 'openai.Completion.createChatCompletion', ([], {'model': 'engine', 'prompt': 'prompt', 'temperature': 'temp', 'max_tokens': 'tokens', 'top_p': 'top_p', 'frequency_penalty': 'freq_pen', 'presence_penalty': 'pres_pen', 'stop': 'stop'}), '(model=engine, prompt=prompt,\n temperature=temp, max_tokens=tokens, top_p=top_p, frequency_penalty=\n freq_pen, presence_penalty=pres_pen, stop=stop)\n', (1170, 1324), False, 'import openai\n'), ((1526, 1555), 're.sub', 're.sub', (["'[\\r\\n]+'", '"""\n"""', 'text'], {}), "('[\\r\\n]+', '\\n', text)\n", (1532, 1555), False, 'import re\n'), ((1577, 1604), 're.sub', 're.sub', (['"""[\t ]+"""', '""" """', 'text'], {}), "('[\\t ]+', ' ', text)\n", (1583, 1604), False, 'import re\n'), ((11026, 11067), 'json.dumps', 'json.dumps', (['initialization_data'], {'indent': '(4)'}), '(initialization_data, indent=4)\n', (11036, 11067), False, 'import json\n'), ((13134, 13141), 'uuid.uuid4', 'uuid4', ([], {}), '()\n', (13139, 13141), False, 'from uuid import uuid4\n'), ((1646, 1652), 'time.time', 'time', ([], {}), '()\n', (1650, 1652), False, 'from time import time, sleep\n'), ((1672, 1699), 'os.path.exists', 'os.path.exists', (['"""gpt3_logs"""'], {}), "('gpt3_logs')\n", (1686, 1699), False, 'import os\n'), ((1719, 1743), 'os.makedirs', 'os.makedirs', (['"""gpt3_logs"""'], {}), "('gpt3_logs')\n", (1730, 1743), False, 'import os\n'), ((2072, 2080), 'time.sleep', 'sleep', (['(1)'], {}), '(1)\n', (2077, 2080), False, 'from time import time, sleep\n')]
import logging import chainlit as cl import lancedb import pandas as pd from langchain import LLMChain from langchain.agents.agent_toolkits import create_conversational_retrieval_agent from langchain.agents.agent_toolkits import create_retriever_tool from langchain.chat_models import ChatOpenAI from langchain.embeddings import OpenAIEmbeddings from langchain.schema import SystemMessage from langchain.vectorstores import LanceDB OPENAI_MODEL = "gpt-3.5-turbo-16k" # "gpt-3.5-turbo" logger = logging.getLogger(__name__) recipes = pd.read_pickle("data/preprocessed/recipes.pkl") recipes.drop_duplicates(subset=["id"], inplace=True) # Must for this dataset recipes.drop("target", axis=1, inplace=True) uri = "dataset/chainlit-recipes-lancedb" db = lancedb.connect(uri) table = db.create_table("recipes", recipes, mode="overwrite") @cl.on_chat_start async def main(): embeddings = OpenAIEmbeddings() docsearch = await cl.make_async(LanceDB)(connection=table, embedding=embeddings) llm = ChatOpenAI(model=OPENAI_MODEL, temperature=0) tool = create_retriever_tool( docsearch.as_retriever(search_kwargs={"k": 10}), # kan kalle denne dynamisk for menyer "recommend_recipes_or_menus", "Recommends dinner recipes or menus based on user preferences. Invocations must be in norwegian.", ) tools = [tool] system_message = SystemMessage( content=( """You are a recommender chatting with the user to provide dinner recipe recommendation. You must follow the instructions below during chat. You can recommend either a recipe plan for a week or single recipes. If you do not have enough information about user preference, you should ask the user for his preference. If you have enough information about user preference, you can give recommendation. The recommendation list can contain items that the dialog mentioned before. Recommendations are given by using the tool recommend_recipes_or_menus with a query you think matches the conversation and user preferences. The query must be in norwegian.""" ) ) qa = create_conversational_retrieval_agent( llm, tools, system_message=system_message, remember_intermediate_steps=True, # max_tokens_limit=4000, verbose=True, ) # Store the chain in the user session cl.user_session.set("llm_chain", qa) @cl.on_message async def main(message: cl.Message): print(message) # Retrieve the chain from the user session llm_chain = cl.user_session.get("llm_chain") # type: LLMChain # Call the chain asynchronously res = await llm_chain.acall(message.content, callbacks=[cl.AsyncLangchainCallbackHandler()]) # Do any post-processing here await cl.Message(content=res["output"]).send() # HOW TO RUN: chainlit run app.py -w
[ "lancedb.connect" ]
[((498, 525), 'logging.getLogger', 'logging.getLogger', (['__name__'], {}), '(__name__)\n', (515, 525), False, 'import logging\n'), ((537, 584), 'pandas.read_pickle', 'pd.read_pickle', (['"""data/preprocessed/recipes.pkl"""'], {}), "('data/preprocessed/recipes.pkl')\n", (551, 584), True, 'import pandas as pd\n'), ((755, 775), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (770, 775), False, 'import lancedb\n'), ((893, 911), 'langchain.embeddings.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (909, 911), False, 'from langchain.embeddings import OpenAIEmbeddings\n'), ((1007, 1052), 'langchain.chat_models.ChatOpenAI', 'ChatOpenAI', ([], {'model': 'OPENAI_MODEL', 'temperature': '(0)'}), '(model=OPENAI_MODEL, temperature=0)\n', (1017, 1052), False, 'from langchain.chat_models import ChatOpenAI\n'), ((1375, 2106), 'langchain.schema.SystemMessage', 'SystemMessage', ([], {'content': '"""You are a recommender chatting with the user to provide dinner recipe recommendation. You must follow the instructions below during chat. You can recommend either a recipe plan for a week or single recipes. \n If you do not have enough information about user preference, you should ask the user for his preference.\n If you have enough information about user preference, you can give recommendation. The recommendation list can contain items that the dialog mentioned before.\n Recommendations are given by using the tool recommend_recipes_or_menus with a query you think matches the conversation and user preferences. The query must be in norwegian."""'}), '(content=\n """You are a recommender chatting with the user to provide dinner recipe recommendation. You must follow the instructions below during chat. You can recommend either a recipe plan for a week or single recipes. \n If you do not have enough information about user preference, you should ask the user for his preference.\n If you have enough information about user preference, you can give recommendation. The recommendation list can contain items that the dialog mentioned before.\n Recommendations are given by using the tool recommend_recipes_or_menus with a query you think matches the conversation and user preferences. The query must be in norwegian."""\n )\n', (1388, 2106), False, 'from langchain.schema import SystemMessage\n'), ((2145, 2278), 'langchain.agents.agent_toolkits.create_conversational_retrieval_agent', 'create_conversational_retrieval_agent', (['llm', 'tools'], {'system_message': 'system_message', 'remember_intermediate_steps': '(True)', 'verbose': '(True)'}), '(llm, tools, system_message=\n system_message, remember_intermediate_steps=True, verbose=True)\n', (2182, 2278), False, 'from langchain.agents.agent_toolkits import create_conversational_retrieval_agent\n'), ((2401, 2437), 'chainlit.user_session.set', 'cl.user_session.set', (['"""llm_chain"""', 'qa'], {}), "('llm_chain', qa)\n", (2420, 2437), True, 'import chainlit as cl\n'), ((2574, 2606), 'chainlit.user_session.get', 'cl.user_session.get', (['"""llm_chain"""'], {}), "('llm_chain')\n", (2593, 2606), True, 'import chainlit as cl\n'), ((934, 956), 'chainlit.make_async', 'cl.make_async', (['LanceDB'], {}), '(LanceDB)\n', (947, 956), True, 'import chainlit as cl\n'), ((2804, 2837), 'chainlit.Message', 'cl.Message', ([], {'content': "res['output']"}), "(content=res['output'])\n", (2814, 2837), True, 'import chainlit as cl\n'), ((2722, 2756), 'chainlit.AsyncLangchainCallbackHandler', 'cl.AsyncLangchainCallbackHandler', ([], {}), '()\n', (2754, 2756), True, 'import chainlit as cl\n')]
import streamlit as st import pandas as pd import json import requests from pathlib import Path from datetime import datetime from jinja2 import Template import lancedb import sqlite3 from services.lancedb_notes import IndexDocumentsNotes st.set_page_config(layout='wide', page_title='Notes') @st.cache_data def summarize_text(text, prompt): system_prompt = '\n'.join(prompt['system_prompt']) content_prompt = Template('\n'.join(prompt['content_prompt'])) content_prompt = content_prompt.render({'text':text}) results = requests.post('http://localhost:8001/summarize', json={'system_prompt':system_prompt, 'content_prompt':content_prompt}) return results.json()['summary'] # @st.cache_data def keyphrase_text(text, strength_cutoff=0.3): results = requests.post('http://localhost:8001/phrases', json={'text':text}) results = results.json() phrases = list() for phrase, strength in zip(results['phrases'], results['strengths']): if strength >= strength_cutoff: phrases.append(phrase) return phrases @st.cache_data def entities_extract(text): results = requests.post('http://localhost:8001/ner', json={'text':text}) # st.write(results.json()['entities']) return results.json()['entities'] @st.cache_data def store_note(note): with open('tmp_json.json','w') as f: json.dump(note, f) return note notes_folder = Path('data/notes') collections_folder = Path('data/collections') tmp_folder = Path('data/tmp') config_folder = Path('data/config') with open(config_folder.joinpath('prompt_templates.json'), 'r') as f: prompt_options = json.load(f) index_folder = Path('indexes') sqlite_location = Path('data/indexes/documents.sqlite') lance_index = lancedb.connect(index_folder) available_indexes = lance_index.table_names() selected_collections = st.multiselect('Which note collections to load', options=available_indexes) index_to_search = st.selectbox(label='Available Indexes', options=available_indexes) prompt_option_choices = [x['Name'] for x in prompt_options] for collection_idx, collection_name in enumerate(selected_collections): sqlite_conn = sqlite3.connect(sqlite_location) notes = sqlite_conn.execute(f"""SELECT * from {collection_name}""").fetchall() fields = sqlite_conn.execute(f"PRAGMA table_info({collection_name})").fetchall() fields = [x[1] for x in fields] notes = [dict(zip(fields, note)) for note in notes] for note in notes: note['metadata'] = json.loads(note['metadata']) with st.expander(collection_name): st.markdown("""Batch processing is possible. Select what you want and whether you want to overwrite the files or save to a new collection.\n\n*If you want to overwrite, leave the collection name as is.*""") batch_phrase, batch_entity, batch_summary = st.columns([1,1,1]) with batch_phrase: batch_phrase_extract = st.toggle('Batch Phrase Extract', key=f'batch_phrase_extract_{collection_name}') with batch_entity: batch_entity_extract = st.toggle('Batch Entity Extract', key=f'batch_entity_extract_{collection_name}') with batch_summary: batch_summary_extract = st.toggle('Batch Summary Extract', key=f'batch_summary_extract_{collection_name}') selected_prompt_name = st.selectbox("Which prompt template?", prompt_option_choices, index=0) selected_prompt = prompt_options[prompt_option_choices.index(selected_prompt_name)] print(selected_prompt) save_collection_name = st.text_input('Saved Notes Collection Name', value=collection_name, key=f'batch_collection_save_{collection_name}') if st.button('Batch Process!', key=f'batch_process_{collection_name}'): progress_text = "Processing Progress (May take some time if summarizing)" batch_progress_bar = st.progress(0, text=progress_text) for i, note in enumerate(notes, start=1): if batch_entity_extract: entities = entities_extract(note['text']) note['entities'] = entities if batch_summary_extract: note['summary'] = summarize_text(note['text'], selected_prompt).strip() batch_progress_bar.progress(i/len(notes), text=progress_text) st.write("Collection Processed!") with st.container(): for index, note in enumerate(notes): st.markdown(f"**:blue[{note['title']}]**") if st.toggle('Show Note', key=f'show_note_{collection_name}_{index}'): text_col, note_col = st.columns([0.6,0.4]) with text_col: st.markdown(f"**Date:** {note['date']}") st.markdown(f"**Title:** {note['title']}") if 'tags' in note and len(note['tags']) > 0: st.markdown(f"**Tags:** {note['tags']}") if 'phrases' in note['metadata']: st.markdown(f"**Keyphrases:** {note['metadata']['phrases']}") if 'entities' in note['metadata']: st.markdown(f"Entities:** {note['metadata']['entities']}") st.markdown("**Text**") st.markdown(note['text'].replace('\n','\n\n')) st.json(note['metadata'], expanded=False) with note_col: ## Create session state for the text ## add button to make rest api call to populate and then update text ## Add button to save the note save_note, local_collection = st.columns([1,3]) with save_note: _save_note = st.button('Save', key=f'save_note_{collection_name}_{index}') ### Keyphrase extraction using Keybert/Keyphrase Vectorizers/Spacy NLP if st.toggle('\nPhrase Extract', key=f'phrase_extract_{collection_name}_{index}'): phrases = keyphrase_text(note['text']) if 'phrases' not in note['metadata']: note['metadata']['phrases'] = ','.join(phrases) else: note['metadata']['phrases'] = note['metadata']['phrases'] +'\n' + ','.join(phrases) if 'phrases' in note['metadata']: note['metadata']['phrases'] = st.text_area('Keyphrases', value=note['metadata']['phrases'], height=100, key=f'phrase_input_{collection_name}_{index}') else: note['metadata']['phrases'] = st.text_area('Keyphrases', value='', height=100, key=f'phrase_input_{collection_name}_{index}') ### Entity extraction using Spacy NLP backend if st.toggle('Entity Extract', key=f'entity_extract_{collection_name}_{index}'): if 'entities' not in note['metadata']: note['metadata']['entities'] = dict() entities = entities_extract(note['text']) note['metadata']['entities'].update(entities) # st.write(note['metadata']['entities']) entities_formatted = '' if 'entities' in note['metadata']: entities_formatted = '' for ent_type, ents in note['metadata']['entities'].items(): ents_text = ', '.join(ents) entities_formatted += f'{ent_type}: {ents_text};\n\n' entities_formatted = entities_formatted.strip() entities_formatted = st.text_area('Entities', value=entities_formatted, height=200, key=f'entity_input_{collection_name}_{index}') else: entities = st.text_area('Entities', value='', height=200, key=f'entity_input_{collection_name}_{index}') note_json = dict() for entity in entities_formatted.split(';'): if len(entity) == 0: continue entity_type, entity_values = entity.split(':') entity_values = [x.strip() for x in entity_values.split(',')] note_json[entity_type.strip()] = entity_values note['metadata']['entities'] = note_json #### Summarization using Llama CPP backend selected_prompt_name = st.selectbox("Which prompt template?", prompt_option_choices, index=0, key=f'doc_prompt_template_{collection_name}_{index}') selected_prompt = prompt_options[prompt_option_choices.index(selected_prompt_name)] if st.toggle('Summarize', key=f'summary_extract_{collection_name}_{index}'): if 'summary' not in note['metadata']: note['metadata']['summary'] = '' summary = summarize_text(note['text'], selected_prompt).strip() note['metadata']['summary'] = summary if 'summary' in note['metadata']: note['metadata']['summary'] = st.text_area('Summary', value=note['metadata']['summary'], height=500, key=f'summary_input_{collection_name}_{index}') else: note['metadata']['summary'] = st.text_area('Summary', value='', height=500, key=f'summary_input_{collection_name}_{index}') if _save_note: note['metadata'] = json.dumps(note['metadata']) lance_table = lance_index.open_table(collection_name) st.write(note['uuid']) # LanceDB current can't (or more likely I don't know) how to update its metadata fields # Sqlite will be used instead as it's the document repository anyways # To create searchable notes, I'll have to think up something with lancedb_notes # lance_table.update(where=f"uuid =' {note['uuid']}'", values={'metadata':note['metadata']}) sqlite_conn.execute(f"""UPDATE {collection_name} SET metadata='{note['metadata'].replace("'","''")}' WHERE uuid='{note['uuid']}'""") sqlite_conn.commit() with st.sidebar: new_collection_name = st.text_input(label='New Collection Name', value='') if st.button('Create Collection'): collections_folder.joinpath(new_collection_name).mkdir(parents=True, exist_ok=True) st.rerun()
[ "lancedb.connect" ]
[((240, 293), 'streamlit.set_page_config', 'st.set_page_config', ([], {'layout': '"""wide"""', 'page_title': '"""Notes"""'}), "(layout='wide', page_title='Notes')\n", (258, 293), True, 'import streamlit as st\n'), ((1504, 1522), 'pathlib.Path', 'Path', (['"""data/notes"""'], {}), "('data/notes')\n", (1508, 1522), False, 'from pathlib import Path\n'), ((1544, 1568), 'pathlib.Path', 'Path', (['"""data/collections"""'], {}), "('data/collections')\n", (1548, 1568), False, 'from pathlib import Path\n'), ((1582, 1598), 'pathlib.Path', 'Path', (['"""data/tmp"""'], {}), "('data/tmp')\n", (1586, 1598), False, 'from pathlib import Path\n'), ((1615, 1634), 'pathlib.Path', 'Path', (['"""data/config"""'], {}), "('data/config')\n", (1619, 1634), False, 'from pathlib import Path\n'), ((1756, 1771), 'pathlib.Path', 'Path', (['"""indexes"""'], {}), "('indexes')\n", (1760, 1771), False, 'from pathlib import Path\n'), ((1790, 1827), 'pathlib.Path', 'Path', (['"""data/indexes/documents.sqlite"""'], {}), "('data/indexes/documents.sqlite')\n", (1794, 1827), False, 'from pathlib import Path\n'), ((1843, 1872), 'lancedb.connect', 'lancedb.connect', (['index_folder'], {}), '(index_folder)\n', (1858, 1872), False, 'import lancedb\n'), ((1942, 2017), 'streamlit.multiselect', 'st.multiselect', (['"""Which note collections to load"""'], {'options': 'available_indexes'}), "('Which note collections to load', options=available_indexes)\n", (1956, 2017), True, 'import streamlit as st\n'), ((2037, 2103), 'streamlit.selectbox', 'st.selectbox', ([], {'label': '"""Available Indexes"""', 'options': 'available_indexes'}), "(label='Available Indexes', options=available_indexes)\n", (2049, 2103), True, 'import streamlit as st\n'), ((557, 682), 'requests.post', 'requests.post', (['"""http://localhost:8001/summarize"""'], {'json': "{'system_prompt': system_prompt, 'content_prompt': content_prompt}"}), "('http://localhost:8001/summarize', json={'system_prompt':\n system_prompt, 'content_prompt': content_prompt})\n", (570, 682), False, 'import requests\n'), ((821, 888), 'requests.post', 'requests.post', (['"""http://localhost:8001/phrases"""'], {'json': "{'text': text}"}), "('http://localhost:8001/phrases', json={'text': text})\n", (834, 888), False, 'import requests\n'), ((1193, 1256), 'requests.post', 'requests.post', (['"""http://localhost:8001/ner"""'], {'json': "{'text': text}"}), "('http://localhost:8001/ner', json={'text': text})\n", (1206, 1256), False, 'import requests\n'), ((1726, 1738), 'json.load', 'json.load', (['f'], {}), '(f)\n', (1735, 1738), False, 'import json\n'), ((2256, 2288), 'sqlite3.connect', 'sqlite3.connect', (['sqlite_location'], {}), '(sqlite_location)\n', (2271, 2288), False, 'import sqlite3\n'), ((11349, 11401), 'streamlit.text_input', 'st.text_input', ([], {'label': '"""New Collection Name"""', 'value': '""""""'}), "(label='New Collection Name', value='')\n", (11362, 11401), True, 'import streamlit as st\n'), ((11409, 11439), 'streamlit.button', 'st.button', (['"""Create Collection"""'], {}), "('Create Collection')\n", (11418, 11439), True, 'import streamlit as st\n'), ((1452, 1470), 'json.dump', 'json.dump', (['note', 'f'], {}), '(note, f)\n', (1461, 1470), False, 'import json\n'), ((2599, 2627), 'json.loads', 'json.loads', (["note['metadata']"], {}), "(note['metadata'])\n", (2609, 2627), False, 'import json\n'), ((2638, 2666), 'streamlit.expander', 'st.expander', (['collection_name'], {}), '(collection_name)\n', (2649, 2666), True, 'import streamlit as st\n'), ((2676, 2890), 'streamlit.markdown', 'st.markdown', (['"""Batch processing is possible. Select what you want and whether you want to overwrite the files or save to a new collection.\n\n*If you want to overwrite, leave the collection name as is.*"""'], {}), '(\n """Batch processing is possible. Select what you want and whether you want to overwrite the files or save to a new collection.\n\n*If you want to overwrite, leave the collection name as is.*"""\n )\n', (2687, 2890), True, 'import streamlit as st\n'), ((2935, 2956), 'streamlit.columns', 'st.columns', (['[1, 1, 1]'], {}), '([1, 1, 1])\n', (2945, 2956), True, 'import streamlit as st\n'), ((3420, 3490), 'streamlit.selectbox', 'st.selectbox', (['"""Which prompt template?"""', 'prompt_option_choices'], {'index': '(0)'}), "('Which prompt template?', prompt_option_choices, index=0)\n", (3432, 3490), True, 'import streamlit as st\n'), ((3645, 3765), 'streamlit.text_input', 'st.text_input', (['"""Saved Notes Collection Name"""'], {'value': 'collection_name', 'key': 'f"""batch_collection_save_{collection_name}"""'}), "('Saved Notes Collection Name', value=collection_name, key=\n f'batch_collection_save_{collection_name}')\n", (3658, 3765), True, 'import streamlit as st\n'), ((3773, 3840), 'streamlit.button', 'st.button', (['"""Batch Process!"""'], {'key': 'f"""batch_process_{collection_name}"""'}), "('Batch Process!', key=f'batch_process_{collection_name}')\n", (3782, 3840), True, 'import streamlit as st\n'), ((11541, 11551), 'streamlit.rerun', 'st.rerun', ([], {}), '()\n', (11549, 11551), True, 'import streamlit as st\n'), ((3017, 3102), 'streamlit.toggle', 'st.toggle', (['"""Batch Phrase Extract"""'], {'key': 'f"""batch_phrase_extract_{collection_name}"""'}), "('Batch Phrase Extract', key=f'batch_phrase_extract_{collection_name}'\n )\n", (3026, 3102), True, 'import streamlit as st\n'), ((3160, 3245), 'streamlit.toggle', 'st.toggle', (['"""Batch Entity Extract"""'], {'key': 'f"""batch_entity_extract_{collection_name}"""'}), "('Batch Entity Extract', key=f'batch_entity_extract_{collection_name}'\n )\n", (3169, 3245), True, 'import streamlit as st\n'), ((3305, 3392), 'streamlit.toggle', 'st.toggle', (['"""Batch Summary Extract"""'], {'key': 'f"""batch_summary_extract_{collection_name}"""'}), "('Batch Summary Extract', key=\n f'batch_summary_extract_{collection_name}')\n", (3314, 3392), True, 'import streamlit as st\n'), ((3961, 3995), 'streamlit.progress', 'st.progress', (['(0)'], {'text': 'progress_text'}), '(0, text=progress_text)\n', (3972, 3995), True, 'import streamlit as st\n'), ((4427, 4460), 'streamlit.write', 'st.write', (['"""Collection Processed!"""'], {}), "('Collection Processed!')\n", (4435, 4460), True, 'import streamlit as st\n'), ((4475, 4489), 'streamlit.container', 'st.container', ([], {}), '()\n', (4487, 4489), True, 'import streamlit as st\n'), ((4556, 4598), 'streamlit.markdown', 'st.markdown', (['f"""**:blue[{note[\'title\']}]**"""'], {}), '(f"**:blue[{note[\'title\']}]**")\n', (4567, 4598), True, 'import streamlit as st\n'), ((4618, 4684), 'streamlit.toggle', 'st.toggle', (['"""Show Note"""'], {'key': 'f"""show_note_{collection_name}_{index}"""'}), "('Show Note', key=f'show_note_{collection_name}_{index}')\n", (4627, 4684), True, 'import streamlit as st\n'), ((4727, 4749), 'streamlit.columns', 'st.columns', (['[0.6, 0.4]'], {}), '([0.6, 0.4])\n', (4737, 4749), True, 'import streamlit as st\n'), ((4808, 4848), 'streamlit.markdown', 'st.markdown', (['f"""**Date:** {note[\'date\']}"""'], {}), '(f"**Date:** {note[\'date\']}")\n', (4819, 4848), True, 'import streamlit as st\n'), ((4873, 4915), 'streamlit.markdown', 'st.markdown', (['f"""**Title:** {note[\'title\']}"""'], {}), '(f"**Title:** {note[\'title\']}")\n', (4884, 4915), True, 'import streamlit as st\n'), ((5373, 5396), 'streamlit.markdown', 'st.markdown', (['"""**Text**"""'], {}), "('**Text**')\n", (5384, 5396), True, 'import streamlit as st\n'), ((5492, 5533), 'streamlit.json', 'st.json', (["note['metadata']"], {'expanded': '(False)'}), "(note['metadata'], expanded=False)\n", (5499, 5533), True, 'import streamlit as st\n'), ((5833, 5851), 'streamlit.columns', 'st.columns', (['[1, 3]'], {}), '([1, 3])\n', (5843, 5851), True, 'import streamlit as st\n'), ((6118, 6196), 'streamlit.toggle', 'st.toggle', (['"""\nPhrase Extract"""'], {'key': 'f"""phrase_extract_{collection_name}_{index}"""'}), "('\\nPhrase Extract', key=f'phrase_extract_{collection_name}_{index}')\n", (6127, 6196), True, 'import streamlit as st\n'), ((7211, 7287), 'streamlit.toggle', 'st.toggle', (['"""Entity Extract"""'], {'key': 'f"""entity_extract_{collection_name}_{index}"""'}), "('Entity Extract', key=f'entity_extract_{collection_name}_{index}')\n", (7220, 7287), True, 'import streamlit as st\n'), ((9176, 9305), 'streamlit.selectbox', 'st.selectbox', (['"""Which prompt template?"""', 'prompt_option_choices'], {'index': '(0)', 'key': 'f"""doc_prompt_template_{collection_name}_{index}"""'}), "('Which prompt template?', prompt_option_choices, index=0, key=\n f'doc_prompt_template_{collection_name}_{index}')\n", (9188, 9305), True, 'import streamlit as st\n'), ((9496, 9568), 'streamlit.toggle', 'st.toggle', (['"""Summarize"""'], {'key': 'f"""summary_extract_{collection_name}_{index}"""'}), "('Summarize', key=f'summary_extract_{collection_name}_{index}')\n", (9505, 9568), True, 'import streamlit as st\n'), ((5013, 5053), 'streamlit.markdown', 'st.markdown', (['f"""**Tags:** {note[\'tags\']}"""'], {}), '(f"**Tags:** {note[\'tags\']}")\n', (5024, 5053), True, 'import streamlit as st\n'), ((5140, 5201), 'streamlit.markdown', 'st.markdown', (['f"""**Keyphrases:** {note[\'metadata\'][\'phrases\']}"""'], {}), '(f"**Keyphrases:** {note[\'metadata\'][\'phrases\']}")\n', (5151, 5201), True, 'import streamlit as st\n'), ((5289, 5347), 'streamlit.markdown', 'st.markdown', (['f"""Entities:** {note[\'metadata\'][\'entities\']}"""'], {}), '(f"Entities:** {note[\'metadata\'][\'entities\']}")\n', (5300, 5347), True, 'import streamlit as st\n'), ((5933, 5994), 'streamlit.button', 'st.button', (['"""Save"""'], {'key': 'f"""save_note_{collection_name}_{index}"""'}), "('Save', key=f'save_note_{collection_name}_{index}')\n", (5942, 5994), True, 'import streamlit as st\n'), ((6679, 6803), 'streamlit.text_area', 'st.text_area', (['"""Keyphrases"""'], {'value': "note['metadata']['phrases']", 'height': '(100)', 'key': 'f"""phrase_input_{collection_name}_{index}"""'}), "('Keyphrases', value=note['metadata']['phrases'], height=100,\n key=f'phrase_input_{collection_name}_{index}')\n", (6691, 6803), True, 'import streamlit as st\n'), ((6953, 7053), 'streamlit.text_area', 'st.text_area', (['"""Keyphrases"""'], {'value': '""""""', 'height': '(100)', 'key': 'f"""phrase_input_{collection_name}_{index}"""'}), "('Keyphrases', value='', height=100, key=\n f'phrase_input_{collection_name}_{index}')\n", (6965, 7053), True, 'import streamlit as st\n'), ((8153, 8267), 'streamlit.text_area', 'st.text_area', (['"""Entities"""'], {'value': 'entities_formatted', 'height': '(200)', 'key': 'f"""entity_input_{collection_name}_{index}"""'}), "('Entities', value=entities_formatted, height=200, key=\n f'entity_input_{collection_name}_{index}')\n", (8165, 8267), True, 'import streamlit as st\n'), ((8396, 8494), 'streamlit.text_area', 'st.text_area', (['"""Entities"""'], {'value': '""""""', 'height': '(200)', 'key': 'f"""entity_input_{collection_name}_{index}"""'}), "('Entities', value='', height=200, key=\n f'entity_input_{collection_name}_{index}')\n", (8408, 8494), True, 'import streamlit as st\n'), ((9975, 10098), 'streamlit.text_area', 'st.text_area', (['"""Summary"""'], {'value': "note['metadata']['summary']", 'height': '(500)', 'key': 'f"""summary_input_{collection_name}_{index}"""'}), "('Summary', value=note['metadata']['summary'], height=500, key=\n f'summary_input_{collection_name}_{index}')\n", (9987, 10098), True, 'import streamlit as st\n'), ((10245, 10343), 'streamlit.text_area', 'st.text_area', (['"""Summary"""'], {'value': '""""""', 'height': '(500)', 'key': 'f"""summary_input_{collection_name}_{index}"""'}), "('Summary', value='', height=500, key=\n f'summary_input_{collection_name}_{index}')\n", (10257, 10343), True, 'import streamlit as st\n'), ((10489, 10517), 'json.dumps', 'json.dumps', (["note['metadata']"], {}), "(note['metadata'])\n", (10499, 10517), False, 'import json\n'), ((10628, 10650), 'streamlit.write', 'st.write', (["note['uuid']"], {}), "(note['uuid'])\n", (10636, 10650), True, 'import streamlit as st\n')]
from langchain.vectorstores import LanceDB import lancedb from langchain.embeddings.openai import OpenAIEmbeddings from langchain.chat_models import ChatOpenAI from langchain.chains import RetrievalQA # load agents and tools modules import pandas as pd from io import StringIO from langchain.tools.python.tool import PythonAstREPLTool from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType from langchain import LLMMathChain from langchain.embeddings import HuggingFaceEmbeddings from langchain.document_loaders import PyPDFLoader, DirectoryLoader from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.llms import CTransformers from langchain.chains import RetrievalQA from langchain.document_loaders import TextLoader from scripts.load_llm import llm_openai class HRChatbot: def __init__(self, df_path, text_data_path, user): self.df_path = df_path self.text_data_path = text_data_path self.user = user self.llm = llm_openai().llm self.df = None self.timekeeping_policy = None self.agent = None self.load_data() self.initialize_tools() def load_data(self): # Load text documents loader = TextLoader(self.text_data_path) docs = loader.load() # Split documents into smaller chunks text_splitter = RecursiveCharacterTextSplitter( chunk_size=100, chunk_overlap=30, ) documents = text_splitter.split_documents(docs) # Create Hugging Face embeddings embeddings = HuggingFaceEmbeddings( model_name="sentence-transformers/all-MiniLM-L6-v2", model_kwargs={"device": "cpu"}, ) # create lancedb vectordb db = lancedb.connect("/tmp/lancedb") table = db.create_table( "pandas_docs", data=[ { "vector": embeddings.embed_query("Hello World"), "text": "Hello World", "id": "1", } ], mode="overwrite", ) self.vectorstore = LanceDB.from_documents( documents, embeddings, connection=table ) self.df = pd.read_csv(self.df_path) def initialize_tools(self): # Initialize retrieval question-answering model # Initialize tools for the agent timekeeping_policy = RetrievalQA.from_chain_type( llm=self.llm, chain_type="stuff", retriever=self.vectorstore.as_retriever(), ) python = PythonAstREPLTool(locals={"df": self.df}) calculator = LLMMathChain.from_llm(llm=self.llm, verbose=True) # Set up variables and descriptions for the tools user = self.user df_columns = self.df.columns.to_list() tools = [ Tool( name="Timekeeping Policies", func=timekeeping_policy.run, description=""" Useful for when you need to answer questions about employee timekeeping policies. <user>: What is the policy on unused vacation leave? <assistant>: I need to check the timekeeping policies to answer this question. <assistant>: Action: Timekeeping Policies <assistant>: Action Input: Vacation Leave Policy - Unused Leave ... """, ), Tool( name="Employee Data", func=python.run, description=f""" Useful for when you need to answer questions about employee data stored in pandas dataframe 'df'. Run python pandas operations on 'df' to help you get the right answer. 'df' has the following columns: {df_columns} <user>: How many Sick Leave do I have left? <assistant>: df[df['name'] == '{user}']['vacation_leave'] <assistant>: You have n vacation_leave left. """, ), Tool( name="Calculator", func=calculator.run, description=f""" Useful when you need to do math operations or arithmetic operations. """, ), ] # Initialize the LLM agent agent_kwargs = { "prefix": f"You are friendly HR assistant. You are tasked to assist the current user: {user} on questions related to HR. ..." } self.timekeeping_policy = timekeeping_policy self.agent = initialize_agent( tools, self.llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs=agent_kwargs, ) def get_response(self, user_input): response = self.agent.run(user_input) return response
[ "lancedb.connect" ]
[((1254, 1285), 'langchain.document_loaders.TextLoader', 'TextLoader', (['self.text_data_path'], {}), '(self.text_data_path)\n', (1264, 1285), False, 'from langchain.document_loaders import TextLoader\n'), ((1386, 1450), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': '(100)', 'chunk_overlap': '(30)'}), '(chunk_size=100, chunk_overlap=30)\n', (1416, 1450), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter\n'), ((1605, 1715), 'langchain.embeddings.HuggingFaceEmbeddings', 'HuggingFaceEmbeddings', ([], {'model_name': '"""sentence-transformers/all-MiniLM-L6-v2"""', 'model_kwargs': "{'device': 'cpu'}"}), "(model_name='sentence-transformers/all-MiniLM-L6-v2',\n model_kwargs={'device': 'cpu'})\n", (1626, 1715), False, 'from langchain.embeddings import HuggingFaceEmbeddings\n'), ((1795, 1826), 'lancedb.connect', 'lancedb.connect', (['"""/tmp/lancedb"""'], {}), "('/tmp/lancedb')\n", (1810, 1826), False, 'import lancedb\n'), ((2167, 2230), 'langchain.vectorstores.LanceDB.from_documents', 'LanceDB.from_documents', (['documents', 'embeddings'], {'connection': 'table'}), '(documents, embeddings, connection=table)\n', (2189, 2230), False, 'from langchain.vectorstores import LanceDB\n'), ((2272, 2297), 'pandas.read_csv', 'pd.read_csv', (['self.df_path'], {}), '(self.df_path)\n', (2283, 2297), True, 'import pandas as pd\n'), ((2626, 2667), 'langchain.tools.python.tool.PythonAstREPLTool', 'PythonAstREPLTool', ([], {'locals': "{'df': self.df}"}), "(locals={'df': self.df})\n", (2643, 2667), False, 'from langchain.tools.python.tool import PythonAstREPLTool\n'), ((2689, 2738), 'langchain.LLMMathChain.from_llm', 'LLMMathChain.from_llm', ([], {'llm': 'self.llm', 'verbose': '(True)'}), '(llm=self.llm, verbose=True)\n', (2710, 2738), False, 'from langchain import LLMMathChain\n'), ((4670, 4794), 'langchain.agents.initialize_agent', 'initialize_agent', (['tools', 'self.llm'], {'agent': 'AgentType.ZERO_SHOT_REACT_DESCRIPTION', 'verbose': '(True)', 'agent_kwargs': 'agent_kwargs'}), '(tools, self.llm, agent=AgentType.\n ZERO_SHOT_REACT_DESCRIPTION, verbose=True, agent_kwargs=agent_kwargs)\n', (4686, 4794), False, 'from langchain.agents import initialize_agent, Tool\n'), ((1018, 1030), 'scripts.load_llm.llm_openai', 'llm_openai', ([], {}), '()\n', (1028, 1030), False, 'from scripts.load_llm import llm_openai\n'), ((2900, 3430), 'langchain.agents.Tool', 'Tool', ([], {'name': '"""Timekeeping Policies"""', 'func': 'timekeeping_policy.run', 'description': '"""\n Useful for when you need to answer questions about employee timekeeping policies.\n\n <user>: What is the policy on unused vacation leave?\n <assistant>: I need to check the timekeeping policies to answer this question.\n <assistant>: Action: Timekeeping Policies\n <assistant>: Action Input: Vacation Leave Policy - Unused Leave\n ...\n """'}), '(name=\'Timekeeping Policies\', func=timekeeping_policy.run, description=\n """\n Useful for when you need to answer questions about employee timekeeping policies.\n\n <user>: What is the policy on unused vacation leave?\n <assistant>: I need to check the timekeeping policies to answer this question.\n <assistant>: Action: Timekeeping Policies\n <assistant>: Action Input: Vacation Leave Policy - Unused Leave\n ...\n """\n )\n', (2904, 3430), False, 'from langchain.agents import initialize_agent, Tool\n'), ((3497, 4078), 'langchain.agents.Tool', 'Tool', ([], {'name': '"""Employee Data"""', 'func': 'python.run', 'description': 'f"""\n Useful for when you need to answer questions about employee data stored in pandas dataframe \'df\'. \n Run python pandas operations on \'df\' to help you get the right answer.\n \'df\' has the following columns: {df_columns}\n \n <user>: How many Sick Leave do I have left?\n <assistant>: df[df[\'name\'] == \'{user}\'][\'vacation_leave\']\n <assistant>: You have n vacation_leave left. \n """'}), '(name=\'Employee Data\', func=python.run, description=\n f"""\n Useful for when you need to answer questions about employee data stored in pandas dataframe \'df\'. \n Run python pandas operations on \'df\' to help you get the right answer.\n \'df\' has the following columns: {df_columns}\n \n <user>: How many Sick Leave do I have left?\n <assistant>: df[df[\'name\'] == \'{user}\'][\'vacation_leave\']\n <assistant>: You have n vacation_leave left. \n """\n )\n', (3501, 4078), False, 'from langchain.agents import initialize_agent, Tool\n'), ((4145, 4322), 'langchain.agents.Tool', 'Tool', ([], {'name': '"""Calculator"""', 'func': 'calculator.run', 'description': 'f"""\n Useful when you need to do math operations or arithmetic operations.\n """'}), '(name=\'Calculator\', func=calculator.run, description=\n f"""\n Useful when you need to do math operations or arithmetic operations.\n """\n )\n', (4149, 4322), False, 'from langchain.agents import initialize_agent, Tool\n')]
import lancedb import numpy as np import pandas as pd global data data = [] global table table = None def get_recommendations(title): pd_data = pd.DataFrame(data) # Table Search result = ( table.search(pd_data[pd_data["title"] == title]["vector"].values[0]) .limit(5) .to_pandas() ) # Get IMDB links links = pd.read_csv( "./ml-latest-small/links.csv", header=0, names=["movie id", "imdb id", "tmdb id"], converters={"imdb id": str}, ) ret = result["title"].values.tolist() # Loop to add links for i in range(len(ret)): link = links[links["movie id"] == result["id"].values[i]]["imdb id"].values[0] link = "https://www.imdb.com/title/tt" + link ret[i] = [ret[i], link] return ret if __name__ == "__main__": # Load and prepare data ratings = pd.read_csv( "./ml-latest-small/ratings.csv", header=None, names=["user id", "movie id", "rating", "timestamp"], ) ratings = ratings.drop(columns=["timestamp"]) ratings = ratings.drop(0) ratings["rating"] = ratings["rating"].values.astype(np.float32) ratings["user id"] = ratings["user id"].values.astype(np.int32) ratings["movie id"] = ratings["movie id"].values.astype(np.int32) reviewmatrix = ratings.pivot( index="user id", columns="movie id", values="rating" ).fillna(0) # SVD matrix = reviewmatrix.values u, s, vh = np.linalg.svd(matrix, full_matrices=False) vectors = np.rot90(np.fliplr(vh)) # Metadata movies = pd.read_csv( "./ml-latest-small/movies.csv", header=0, names=["movie id", "title", "genres"] ) movies = movies[movies["movie id"].isin(reviewmatrix.columns)] data = [] for i in range(len(movies)): data.append( { "id": movies.iloc[i]["movie id"], "title": movies.iloc[i]["title"], "vector": vectors[i], "genre": movies.iloc[i]["genres"], } ) # Connect to LanceDB db_url = "your-project-name" api_key = "sk_..." region = "us-east-1" db = lancedb.connect(db_url, api_key=api_key, region=region) try: table = db.create_table("movie_set", data=data) except: table = db.open_table("movie_set") print(get_recommendations("Moana (2016)")) print(get_recommendations("Rogue One: A Star Wars Story (2016)"))
[ "lancedb.connect" ]
[((152, 170), 'pandas.DataFrame', 'pd.DataFrame', (['data'], {}), '(data)\n', (164, 170), True, 'import pandas as pd\n'), ((361, 488), 'pandas.read_csv', 'pd.read_csv', (['"""./ml-latest-small/links.csv"""'], {'header': '(0)', 'names': "['movie id', 'imdb id', 'tmdb id']", 'converters': "{'imdb id': str}"}), "('./ml-latest-small/links.csv', header=0, names=['movie id',\n 'imdb id', 'tmdb id'], converters={'imdb id': str})\n", (372, 488), True, 'import pandas as pd\n'), ((880, 995), 'pandas.read_csv', 'pd.read_csv', (['"""./ml-latest-small/ratings.csv"""'], {'header': 'None', 'names': "['user id', 'movie id', 'rating', 'timestamp']"}), "('./ml-latest-small/ratings.csv', header=None, names=['user id',\n 'movie id', 'rating', 'timestamp'])\n", (891, 995), True, 'import pandas as pd\n'), ((1480, 1522), 'numpy.linalg.svd', 'np.linalg.svd', (['matrix'], {'full_matrices': '(False)'}), '(matrix, full_matrices=False)\n', (1493, 1522), True, 'import numpy as np\n'), ((1591, 1687), 'pandas.read_csv', 'pd.read_csv', (['"""./ml-latest-small/movies.csv"""'], {'header': '(0)', 'names': "['movie id', 'title', 'genres']"}), "('./ml-latest-small/movies.csv', header=0, names=['movie id',\n 'title', 'genres'])\n", (1602, 1687), True, 'import pandas as pd\n'), ((2178, 2233), 'lancedb.connect', 'lancedb.connect', (['db_url'], {'api_key': 'api_key', 'region': 'region'}), '(db_url, api_key=api_key, region=region)\n', (2193, 2233), False, 'import lancedb\n'), ((1547, 1560), 'numpy.fliplr', 'np.fliplr', (['vh'], {}), '(vh)\n', (1556, 1560), True, 'import numpy as np\n')]
import lancedb from datasets import load_dataset import pandas as pd import numpy as np from hyperdemocracy.embedding.models import BGESmallEn class Lance: def __init__(self): self.model = BGESmallEn() uri = "data/sample-lancedb" self.db = lancedb.connect(uri) def create_table(self): ds = load_dataset("hyperdemocracy/uscb.s1024.o256.bge-small-en", split="train") df = pd.DataFrame(ds) df.rename(columns={"vec": "vector"}, inplace=True) table = self.db.create_table("congress", data=df) return def query_table(self, queries, n=5) -> pd.DataFrame: q_embeddings = self.model.model.encode_queries(queries) table = self.db.open_table("congress") result = table.search(q_embeddings.reshape(384,)).limit(n).to_df() return result
[ "lancedb.connect" ]
[((203, 215), 'hyperdemocracy.embedding.models.BGESmallEn', 'BGESmallEn', ([], {}), '()\n', (213, 215), False, 'from hyperdemocracy.embedding.models import BGESmallEn\n'), ((270, 290), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (285, 290), False, 'import lancedb\n'), ((333, 407), 'datasets.load_dataset', 'load_dataset', (['"""hyperdemocracy/uscb.s1024.o256.bge-small-en"""'], {'split': '"""train"""'}), "('hyperdemocracy/uscb.s1024.o256.bge-small-en', split='train')\n", (345, 407), False, 'from datasets import load_dataset\n'), ((421, 437), 'pandas.DataFrame', 'pd.DataFrame', (['ds'], {}), '(ds)\n', (433, 437), True, 'import pandas as pd\n')]
import lancedb uri = "test_data" db = lancedb.connect(uri) tbl = db.create_table("my_table", data=[{"vector": [3.1, 4.1], "item": "foo", "price": 10.0}, {"vector": [5.9, 26.5], "item": "bar", "price": 20.0}])
[ "lancedb.connect" ]
[((38, 58), 'lancedb.connect', 'lancedb.connect', (['uri'], {}), '(uri)\n', (53, 58), False, 'import lancedb\n')]
# Copyright 2023 LanceDB Developers # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import random from unittest import mock import lancedb as ldb import numpy as np import pandas as pd import pytest pytest.importorskip("lancedb.fts") tantivy = pytest.importorskip("tantivy") @pytest.fixture def table(tmp_path) -> ldb.table.LanceTable: db = ldb.connect(tmp_path) vectors = [np.random.randn(128) for _ in range(100)] nouns = ("puppy", "car", "rabbit", "girl", "monkey") verbs = ("runs", "hits", "jumps", "drives", "barfs") adv = ("crazily.", "dutifully.", "foolishly.", "merrily.", "occasionally.") adj = ("adorable", "clueless", "dirty", "odd", "stupid") text = [ " ".join( [ nouns[random.randrange(0, 5)], verbs[random.randrange(0, 5)], adv[random.randrange(0, 5)], adj[random.randrange(0, 5)], ] ) for _ in range(100) ] table = db.create_table( "test", data=pd.DataFrame( { "vector": vectors, "id": [i % 2 for i in range(100)], "text": text, "text2": text, "nested": [{"text": t} for t in text], } ), ) return table def test_create_index(tmp_path): index = ldb.fts.create_index(str(tmp_path / "index"), ["text"]) assert isinstance(index, tantivy.Index) assert os.path.exists(str(tmp_path / "index")) def test_populate_index(tmp_path, table): index = ldb.fts.create_index(str(tmp_path / "index"), ["text"]) assert ldb.fts.populate_index(index, table, ["text"]) == len(table) def test_search_index(tmp_path, table): index = ldb.fts.create_index(str(tmp_path / "index"), ["text"]) ldb.fts.populate_index(index, table, ["text"]) index.reload() results = ldb.fts.search_index(index, query="puppy", limit=10) assert len(results) == 2 assert len(results[0]) == 10 # row_ids assert len(results[1]) == 10 # _distance def test_create_index_from_table(tmp_path, table): table.create_fts_index("text") df = table.search("puppy").limit(10).select(["text"]).to_pandas() assert len(df) <= 10 assert "text" in df.columns # Check whether it can be updated table.add( [ { "vector": np.random.randn(128), "id": 101, "text": "gorilla", "text2": "gorilla", "nested": {"text": "gorilla"}, } ] ) with pytest.raises(ValueError, match="already exists"): table.create_fts_index("text") table.create_fts_index("text", replace=True) assert len(table.search("gorilla").limit(1).to_pandas()) == 1 def test_create_index_multiple_columns(tmp_path, table): table.create_fts_index(["text", "text2"]) df = table.search("puppy").limit(10).to_pandas() assert len(df) == 10 assert "text" in df.columns assert "text2" in df.columns def test_empty_rs(tmp_path, table, mocker): table.create_fts_index(["text", "text2"]) mocker.patch("lancedb.fts.search_index", return_value=([], [])) df = table.search("puppy").limit(10).to_pandas() assert len(df) == 0 def test_nested_schema(tmp_path, table): table.create_fts_index("nested.text") rs = table.search("puppy").limit(10).to_list() assert len(rs) == 10 def test_search_index_with_filter(table): table.create_fts_index("text") orig_import = __import__ def import_mock(name, *args): if name == "duckdb": raise ImportError return orig_import(name, *args) # no duckdb with mock.patch("builtins.__import__", side_effect=import_mock): rs = table.search("puppy").where("id=1").limit(10) # test schema assert rs.to_arrow().drop("score").schema.equals(table.schema) rs = rs.to_list() for r in rs: assert r["id"] == 1 # yes duckdb rs2 = table.search("puppy").where("id=1").limit(10).to_list() for r in rs2: assert r["id"] == 1 assert rs == rs2 rs = table.search("puppy").where("id=1").with_row_id(True).limit(10).to_list() for r in rs: assert r["id"] == 1 assert r["_rowid"] is not None def test_null_input(table): table.add( [ { "vector": np.random.randn(128), "id": 101, "text": None, "text2": None, "nested": {"text": None}, } ] ) table.create_fts_index("text") def test_syntax(table): # https://github.com/lancedb/lancedb/issues/769 table.create_fts_index("text") with pytest.raises(ValueError, match="Syntax Error"): table.search("they could have been dogs OR cats").limit(10).to_list() # these should work # terms queries table.search('"they could have been dogs" OR cats').limit(10).to_list() table.search("(they AND could) OR (have AND been AND dogs) OR cats").limit( 10 ).to_list() # phrase queries table.search("they could have been dogs OR cats").phrase_query().limit(10).to_list() table.search('"they could have been dogs OR cats"').limit(10).to_list() table.search('''"the cats OR dogs were not really 'pets' at all"''').limit( 10 ).to_list() table.search('the cats OR dogs were not really "pets" at all').phrase_query().limit( 10 ).to_list() table.search('the cats OR dogs were not really "pets" at all').phrase_query().limit( 10 ).to_list()
[ "lancedb.connect", "lancedb.fts.populate_index", "lancedb.fts.search_index" ]
[((716, 750), 'pytest.importorskip', 'pytest.importorskip', (['"""lancedb.fts"""'], {}), "('lancedb.fts')\n", (735, 750), False, 'import pytest\n'), ((761, 791), 'pytest.importorskip', 'pytest.importorskip', (['"""tantivy"""'], {}), "('tantivy')\n", (780, 791), False, 'import pytest\n'), ((864, 885), 'lancedb.connect', 'ldb.connect', (['tmp_path'], {}), '(tmp_path)\n', (875, 885), True, 'import lancedb as ldb\n'), ((2318, 2364), 'lancedb.fts.populate_index', 'ldb.fts.populate_index', (['index', 'table', "['text']"], {}), "(index, table, ['text'])\n", (2340, 2364), True, 'import lancedb as ldb\n'), ((2398, 2450), 'lancedb.fts.search_index', 'ldb.fts.search_index', (['index'], {'query': '"""puppy"""', 'limit': '(10)'}), "(index, query='puppy', limit=10)\n", (2418, 2450), True, 'import lancedb as ldb\n'), ((901, 921), 'numpy.random.randn', 'np.random.randn', (['(128)'], {}), '(128)\n', (916, 921), True, 'import numpy as np\n'), ((2143, 2189), 'lancedb.fts.populate_index', 'ldb.fts.populate_index', (['index', 'table', "['text']"], {}), "(index, table, ['text'])\n", (2165, 2189), True, 'import lancedb as ldb\n'), ((3096, 3145), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""already exists"""'}), "(ValueError, match='already exists')\n", (3109, 3145), False, 'import pytest\n'), ((4216, 4274), 'unittest.mock.patch', 'mock.patch', (['"""builtins.__import__"""'], {'side_effect': 'import_mock'}), "('builtins.__import__', side_effect=import_mock)\n", (4226, 4274), False, 'from unittest import mock\n'), ((5261, 5308), 'pytest.raises', 'pytest.raises', (['ValueError'], {'match': '"""Syntax Error"""'}), "(ValueError, match='Syntax Error')\n", (5274, 5308), False, 'import pytest\n'), ((2889, 2909), 'numpy.random.randn', 'np.random.randn', (['(128)'], {}), '(128)\n', (2904, 2909), True, 'import numpy as np\n'), ((4922, 4942), 'numpy.random.randn', 'np.random.randn', (['(128)'], {}), '(128)\n', (4937, 4942), True, 'import numpy as np\n'), ((1266, 1288), 'random.randrange', 'random.randrange', (['(0)', '(5)'], {}), '(0, 5)\n', (1282, 1288), False, 'import random\n'), ((1313, 1335), 'random.randrange', 'random.randrange', (['(0)', '(5)'], {}), '(0, 5)\n', (1329, 1335), False, 'import random\n'), ((1358, 1380), 'random.randrange', 'random.randrange', (['(0)', '(5)'], {}), '(0, 5)\n', (1374, 1380), False, 'import random\n'), ((1403, 1425), 'random.randrange', 'random.randrange', (['(0)', '(5)'], {}), '(0, 5)\n', (1419, 1425), False, 'import random\n')]
import pytest import os import openai import argparse import lancedb import re import pickle import requests import zipfile from pathlib import Path from main import get_document_title from langchain.document_loaders import BSHTMLLoader from langchain.embeddings import OpenAIEmbeddings from langchain.text_splitter import RecursiveCharacterTextSplitter from langchain.vectorstores import LanceDB from langchain.llms import OpenAI from langchain.chains import RetrievalQA # TESTING =============================================================== @pytest.fixture def mock_embed(monkeypatch): def mock_embed_query(query, x): return [0.5, 0.5] monkeypatch.setattr(OpenAIEmbeddings, "embed_query", mock_embed_query) def test_main(mock_embed): os.mkdir("./tmp") args = argparse.Namespace(query="test", openai_key="test") os.environ["OPENAI_API_KEY"] = "test" docs_path = Path("docs.pkl") docs = [] pandas_docs = requests.get( "https://eto-public.s3.us-west-2.amazonaws.com/datasets/pandas_docs/pandas.documentation.zip" ) with open("./tmp/pandas.documentation.zip", "wb") as f: f.write(pandas_docs.content) file = zipfile.ZipFile("./tmp/pandas.documentation.zip") file.extractall(path="./tmp/pandas_docs") if not docs_path.exists(): for p in Path("./tmp/pandas_docs/pandas.documentation").rglob("*.html"): print(p) if p.is_dir(): continue loader = BSHTMLLoader(p, open_encoding="utf8") raw_document = loader.load() m = {} m["title"] = get_document_title(raw_document[0]) m["version"] = "2.0rc0" raw_document[0].metadata = raw_document[0].metadata | m raw_document[0].metadata["source"] = str(raw_document[0].metadata["source"]) docs = docs + raw_document with docs_path.open("wb") as fh: pickle.dump(docs, fh) else: with docs_path.open("rb") as fh: docs = pickle.load(fh) text_splitter = RecursiveCharacterTextSplitter( chunk_size=1000, chunk_overlap=200, ) documents = text_splitter.split_documents(docs) db = lancedb.connect("./tmp/lancedb") table = db.create_table( "pandas_docs", data=[ { "vector": OpenAIEmbeddings().embed_query("Hello World"), "text": "Hello World", "id": "1", } ], mode="overwrite", ) # docsearch = LanceDB.from_documents(documents, OpenAIEmbeddings, connection=table) # qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever()) # result = qa.run(args.query) # print(result)
[ "lancedb.connect" ]
[((766, 783), 'os.mkdir', 'os.mkdir', (['"""./tmp"""'], {}), "('./tmp')\n", (774, 783), False, 'import os\n'), ((795, 846), 'argparse.Namespace', 'argparse.Namespace', ([], {'query': '"""test"""', 'openai_key': '"""test"""'}), "(query='test', openai_key='test')\n", (813, 846), False, 'import argparse\n'), ((906, 922), 'pathlib.Path', 'Path', (['"""docs.pkl"""'], {}), "('docs.pkl')\n", (910, 922), False, 'from pathlib import Path\n'), ((956, 1073), 'requests.get', 'requests.get', (['"""https://eto-public.s3.us-west-2.amazonaws.com/datasets/pandas_docs/pandas.documentation.zip"""'], {}), "(\n 'https://eto-public.s3.us-west-2.amazonaws.com/datasets/pandas_docs/pandas.documentation.zip'\n )\n", (968, 1073), False, 'import requests\n'), ((1187, 1236), 'zipfile.ZipFile', 'zipfile.ZipFile', (['"""./tmp/pandas.documentation.zip"""'], {}), "('./tmp/pandas.documentation.zip')\n", (1202, 1236), False, 'import zipfile\n'), ((2065, 2131), 'langchain.text_splitter.RecursiveCharacterTextSplitter', 'RecursiveCharacterTextSplitter', ([], {'chunk_size': '(1000)', 'chunk_overlap': '(200)'}), '(chunk_size=1000, chunk_overlap=200)\n', (2095, 2131), False, 'from langchain.text_splitter import RecursiveCharacterTextSplitter\n'), ((2217, 2249), 'lancedb.connect', 'lancedb.connect', (['"""./tmp/lancedb"""'], {}), "('./tmp/lancedb')\n", (2232, 2249), False, 'import lancedb\n'), ((1490, 1527), 'langchain.document_loaders.BSHTMLLoader', 'BSHTMLLoader', (['p'], {'open_encoding': '"""utf8"""'}), "(p, open_encoding='utf8')\n", (1502, 1527), False, 'from langchain.document_loaders import BSHTMLLoader\n'), ((1614, 1649), 'main.get_document_title', 'get_document_title', (['raw_document[0]'], {}), '(raw_document[0])\n', (1632, 1649), False, 'from main import get_document_title\n'), ((1936, 1957), 'pickle.dump', 'pickle.dump', (['docs', 'fh'], {}), '(docs, fh)\n', (1947, 1957), False, 'import pickle\n'), ((2028, 2043), 'pickle.load', 'pickle.load', (['fh'], {}), '(fh)\n', (2039, 2043), False, 'import pickle\n'), ((1332, 1378), 'pathlib.Path', 'Path', (['"""./tmp/pandas_docs/pandas.documentation"""'], {}), "('./tmp/pandas_docs/pandas.documentation')\n", (1336, 1378), False, 'from pathlib import Path\n'), ((2357, 2375), 'langchain.embeddings.OpenAIEmbeddings', 'OpenAIEmbeddings', ([], {}), '()\n', (2373, 2375), False, 'from langchain.embeddings import OpenAIEmbeddings\n')]