mirror of
https://github.com/neuml/txtai.git
synced 2026-10-12 02:19:52 +00:00
258 KiB
258 KiB
In [ ]:
%%capture
!pip install git+https://github.com/neuml/txtai#egg=txtai[pipeline] textdistance
# Get test data
!wget -N https://github.com/neuml/txtai/releases/download/v3.5.0/tests.tar.gz
!tar -xvzf tests.tar.gzIn [ ]:
import glob
from PIL import Image
from txtai.pipeline import ImageHash
def show(image):
width, height = image.size
return image.resize((int(width / 2.25), int((width / 2.25) * height / width)))
# Get and scale images
images = [Image.open(image) for image in glob.glob('txtai/*jpg')]
# Create image pipeline
ihash = ImageHash()
# Generate hashes
hashes = ihash(images)
hashes['ffffdf0700010100', '78f8f8d8f8f8f8f0', '00000006fefcfc30', '000000c0feffff00', '63263c183ce66742', '60607072fe78cc00', '0859dd04bfbfbf00', '0000446c6f2f2724', 'ff9f010909010101', 'ff9d8140c070ffff']
In [ ]:
# Get test image index
index = hashes.index('000000c0feffff00')
# Select portion of image
width, height = images[index].size
# Get dimensions for middle of image
left = (width - width/3)/2
top = (height - height/1.35)/2
right = (width + width/3)/2
bottom = (height + height/1.35)/2
# Crop image
search = images[index].crop((left, top, right, bottom))
show(search)In [ ]:
import textdistance
# Find closest image hash using textdistance
shash = ihash(search)
# Calculate distances for search hash
distances = [int(textdistance.levenshtein.distance(h, shash)) for h in hashes]
# Show closest image hash
low = min(distances)
show(images[distances.index(low)])In [ ]:
from txtai.embeddings import Embeddings
def distance(a, b):
if a and not b:
return len(a)
if not a and b:
return len(b)
if not a and not b:
return 0
return int(textdistance.levenshtein.distance(a, b))
# Create embeddings index with content enabled. The default behavior is to only store indexed vectors.
embeddings = Embeddings({"path": "sentence-transformers/nli-mpnet-base-v2", "content": True, "objects": "image", "functions": [distance]})
# Create an index for the list of text
embeddings.index([(uid, {"object": image, "text": ihash(image)}, None) for uid, image in enumerate(images)])
# Find image that is closest to hash
show(embeddings.search(f"select object from txtai order by distance(text, '{shash}')")[0]["object"])