Skip to content

armgit / txtai

Public Imported from GitHub
0

πŸ’‘ All-in-one AI framework for semantic search, LLM orchestration and language model workflows

Update example applications for consistency. Add links to applications hosted on hf spaces. Closes #140

davidmezzetti1678b45bd636
diff --git a/README.md b/README.md
index 58b6e710..c8b86d81 100644
--- a/README.md
+++ b/README.md
@@ -134,8 +134,8 @@ Series of example applications with txtai. Links to hosted versions on [Hugging
| Application | Description | |
|:-------------|:-------------|------:|
-| [Demo query shell](https://github.com/neuml/txtai/blob/master/examples/demo.py) | Basic similarity search example. Used in the original txtai demo. ||
-| [Book search](https://github.com/neuml/txtai/blob/master/examples/books.py) | Book similarity search application. Index book descriptions and query using natural language statements. ||
+| [Basic similarity search](https://github.com/neuml/txtai/blob/master/examples/similarity.py) | Basic similarity search example. Data from the original txtai demo. |[πŸ€—](https://hf.co/spaces/NeuML/similarity)|
+| [Book search](https://github.com/neuml/txtai/blob/master/examples/books.py) | Book similarity search application. Index book descriptions and query using natural language statements. |*Local run only*|
| [Image search](https://github.com/neuml/txtai/blob/master/examples/images.py) | Image similarity search application. Index a directory of images and run searches to identify images similar to the input query. |[πŸ€—](https://hf.co/spaces/NeuML/imagesearch)|
| [Wiki search](https://github.com/neuml/txtai/blob/master/examples/wiki.py) | Wikipedia search application. Queries Wikipedia API and summarizes the top result. |[πŸ€—](https://hf.co/spaces/NeuML/wikisummary)|
| [Workflow builder](https://github.com/neuml/txtai/blob/master/examples/workflows.py) | Build and execute txtai workflows. Connect summarization, text extraction, transcription, translation and similarity search pipelines together to run unified workflows. |[πŸ€—](https://hf.co/spaces/NeuML/txtai)|
diff --git a/docs/examples.md b/docs/examples.md
index a2e076ef..4e88db43 100644
--- a/docs/examples.md
+++ b/docs/examples.md
@@ -51,8 +51,8 @@ Series of example applications with txtai. Links to hosted versions on [Hugging
| Application | Description | |
|:-------------|:-------------|------:|
-| [Demo query shell](https://github.com/neuml/txtai/blob/master/examples/demo.py) | Basic similarity search example. Used in the original txtai demo. ||
-| [Book search](https://github.com/neuml/txtai/blob/master/examples/books.py) | Book similarity search application. Index book descriptions and query using natural language statements. ||
+| [Basic similarity search](https://github.com/neuml/txtai/blob/master/examples/similarity.py) | Basic similarity search example. Data from the original txtai demo. |[πŸ€—](https://hf.co/spaces/NeuML/similarity)|
+| [Book search](https://github.com/neuml/txtai/blob/master/examples/books.py) | Book similarity search application. Index book descriptions and query using natural language statements. |*Local run only*|
| [Image search](https://github.com/neuml/txtai/blob/master/examples/images.py) | Image similarity search application. Index a directory of images and run searches to identify images similar to the input query. |[πŸ€—](https://hf.co/spaces/NeuML/imagesearch)|
| [Wiki search](https://github.com/neuml/txtai/blob/master/examples/wiki.py) | Wikipedia search application. Queries Wikipedia API and summarizes the top result. |[πŸ€—](https://hf.co/spaces/NeuML/wikisummary)|
| [Workflow builder](https://github.com/neuml/txtai/blob/master/examples/workflows.py) | Build and execute txtai workflows. Connect summarization, text extraction, transcription, translation and similarity search pipelines together to run unified workflows. |[πŸ€—](https://hf.co/spaces/NeuML/txtai)|
diff --git a/examples/demo.py b/examples/demo.py
deleted file mode 100644
index f92e7cab..00000000
--- a/examples/demo.py
+++ /dev/null
@@ -1,53 +0,0 @@
-"""
-Demo shell
-"""
-
-from cmd import Cmd
-
-from txtai.embeddings import Embeddings
-
-
-class Shell(Cmd):
- """
- Query shell.
- """
-
- def __init__(self):
- super().__init__()
-
- self.intro = "query shell"
- self.prompt = "(search) "
-
- self.embeddings = None
- self.data = None
-
- def preloop(self):
- # Create embeddings model, backed by sentence-transformers & transformers
- self.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
-
- self.data = [
- "US tops 5 million confirmed virus cases",
- "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
- "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
- "The National Park Service warns against sacrificing slower friends in a bear attack",
- "Maine man wins $1M from $25 lottery ticket",
- "Make huge profits without work, earn up to $100,000 a day",
- ]
-
- def default(self, line):
- # Get index of best section that best matches query
- uid = self.embeddings.similarity(line, self.data)[0][0]
- print(self.data[uid])
- print()
-
-
-def main():
- """
- Shell execution loop.
- """
-
- Shell().cmdloop()
-
-
-if __name__ == "__main__":
- main()
diff --git a/examples/images.py b/examples/images.py
index 510a383d..3216d2e1 100644
--- a/examples/images.py
+++ b/examples/images.py
@@ -1,8 +1,8 @@
"""
-Streamlit version of https://colab.research.google.com/github/neuml/txtai/blob/master/examples/13_Similarity_search_with_images.ipynb
+Builds a similarity index for a directory of images
-Requires streamlit and torchvision to be installed.
- pip install streamlit torchvision
+Requires streamlit to be installed.
+ pip install streamlit
"""
import glob
@@ -16,67 +16,90 @@ from PIL import Image
from txtai.embeddings import Embeddings
-def images(directory):
+class Application:
"""
- Generator that loops over each image in a directory.
-
- Args:
- directory: directory with images
+ Main application
"""
- for path in glob.glob(directory + "/*jpg") + glob.glob(directory + "/*png"):
- yield (path, Image.open(path), None)
+ def __init__(self, directory):
+ """
+ Creates a new application.
+ Args:
+ directory: directory of images
+ """
[email protected](allow_output_mutation=True)
-def build(directory):
- """
- Builds an image embeddings index.
+ self.embeddings = self.build(directory)
- Args:
- directory: directory with images
+ def build(self, directory):
+ """
+ Builds an image embeddings index.
- Returns:
- Embeddings index
- """
+ Args:
+ directory: directory with images
- embeddings = Embeddings({"method": "sentence-transformers", "path": "clip-ViT-B-32"})
- embeddings.index(images(directory))
+ Returns:
+ Embeddings index
+ """
- # Update model to support multilingual queries
- embeddings.config["path"] = "sentence-transformers/clip-ViT-B-32-multilingual-v1"
- embeddings.model = embeddings.loadVectors()
+ embeddings = Embeddings({"method": "sentence-transformers", "path": "clip-ViT-B-32"})
+ embeddings.index(self.images(directory))
- return embeddings
+ # Update model to support multilingual queries
+ embeddings.config["path"] = "sentence-transformers/clip-ViT-B-32-multilingual-v1"
+ embeddings.model = embeddings.loadVectors()
+ return embeddings
-def app(directory):
- """
- Streamlit application that runs searches against an image embeddings index.
+ def images(self, directory):
+ """
+ Generator that loops over each image in a directory.
- Args:
- directory: directory with images
- """
+ Args:
+ directory: directory with images
+ """
+
+ for path in glob.glob(directory + "/*jpg") + glob.glob(directory + "/*png"):
+ yield (path, Image.open(path), None)
- # Build embeddings index
- embeddings = build(directory)
+ def run(self):
+ """
+ Runs a Streamlit application.
+ """
- st.title("Image search")
+ st.title("Image search")
- st.markdown("This application shows how images and text can be embedded into the same space to support similarity search. ")
- st.markdown(
- "[sentence-transformers](https://github.com/UKPLab/sentence-transformers/tree/master/examples/applications/image-search) "
- + "recently added support for the [OpenAI CLIP model](https://github.com/openai/CLIP). This model embeds text and images into "
- + "the same space, enabling image similarity search. txtai can directly utilize these models."
- )
+ st.markdown("This application shows how images and text can be embedded into the same space to support similarity search. ")
+ st.markdown(
+ "[sentence-transformers](https://github.com/UKPLab/sentence-transformers/tree/master/examples/applications/image-search) "
+ + "recently added support for the [OpenAI CLIP model](https://github.com/openai/CLIP). This model embeds text and images into "
+ + "the same space, enabling image similarity search. txtai can directly utilize these models."
+ )
+
+ query = st.text_input("Search query:")
+ if query:
+ index, _ = self.embeddings.search(query, 1)[0]
+ st.image(Image.open(index))
+
+
[email protected](allow_output_mutation=True)
+def create(directory):
+ """
+ Creates and caches a Streamlit application.
+
+ Args:
+ directory: directory of images to index
+
+ Returns:
+ Application
+ """
- query = st.text_input("Search query:")
- if query:
- index, _ = embeddings.search(query, 1)[0]
- st.image(Image.open(index))
+ return Application(directory)
if __name__ == "__main__":
os.environ["TOKENIZERS_PARALLELISM"] = "false"
- app(sys.argv[1])
+ # Create and run application
+ app = create(sys.argv[1])
+ app.run()
diff --git a/examples/similarity.py b/examples/similarity.py
new file mode 100644
index 00000000..530e348b
--- /dev/null
+++ b/examples/similarity.py
@@ -0,0 +1,73 @@
+"""
+Basic similarity search example. Used in the original txtai demo.
+
+Requires streamlit to be installed.
+ pip install streamlit
+"""
+
+import os
+
+import streamlit as st
+
+from txtai.embeddings import Embeddings
+
+
+class Application:
+ """
+ Main application.
+ """
+
+ def __init__(self):
+ """
+ Creates a new application.
+ """
+
+ # Create embeddings model, backed by sentence-transformers & transformers
+ self.embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2"})
+
+ def run(self):
+ """
+ Runs a Streamlit application.
+ """
+
+ st.title("Similarity Search")
+ st.markdown("This application runs a basic similarity search that identifies the best matching row for a query.")
+
+ data = [
+ "US tops 5 million confirmed virus cases",
+ "Canada's last fully intact ice shelf has suddenly collapsed, forming a Manhattan-sized iceberg",
+ "Beijing mobilises invasion craft along coast as Taiwan tensions escalate",
+ "The National Park Service warns against sacrificing slower friends in a bear attack",
+ "Maine man wins $1M from $25 lottery ticket",
+ "Make huge profits without work, earn up to $100,000 a day",
+ ]
+
+ data = st.text_area("Data", value="\n".join(data))
+ query = st.text_input("Query")
+
+ data = data.split("\n")
+
+ if query:
+ # Get index of best section that best matches query
+ uid = self.embeddings.similarity(query, data)[0][0]
+ st.write(data[uid])
+
+
[email protected](allow_output_mutation=True)
+def create():
+ """
+ Creates and caches a Streamlit application.
+
+ Returns:
+ Application
+ """
+
+ return Application()
+
+
+if __name__ == "__main__":
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
+
+ # Create and run application
+ app = create()
+ app.run()
diff --git a/examples/wiki.py b/examples/wiki.py
index 4898d9fa..3eaefc90 100644
--- a/examples/wiki.py
+++ b/examples/wiki.py
@@ -1,11 +1,8 @@
"""
Application that queries Wikipedia API and summarizes the top result.
-Install Streamlit
+Requires streamlit to be installed.
pip install streamlit
-
-Run application
- streamlit run wiki.py
"""
import os
diff --git a/examples/workflows.py b/examples/workflows.py
index 120f5840..f2b0e07e 100644
--- a/examples/workflows.py
+++ b/examples/workflows.py
@@ -64,12 +64,12 @@ class Server(uvicorn.Server):
class Application:
"""
- Streamlit application.
+ Main application.
"""
def __init__(self):
"""
- Creates a new Streamlit application.
+ Creates a new application.
"""
# Component options