Skip to content

Instantly share code, notes, and snippets.

@tarekziade
Created January 18, 2024 09:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tarekziade/32eeadc114897fcd043e1616ed087577 to your computer and use it in GitHub Desktop.
Save tarekziade/32eeadc114897fcd043e1616ed087577 to your computer and use it in GitHub Desktop.
imagenet_hypernyms.py
import sys
import nltk
from nltk.corpus import wordnet as wn
nltk.download("wordnet")
def find_hypernyms(synset_name):
synset = wn.synset(synset_name)
hypernyms = synset.hypernyms()
if not hypernyms:
return [synset_name]
return [synset_name] + find_hypernyms(hypernyms[0].name())
def hyper2text(word):
word = word.split(".")[0]
return word.lower().replace("_", " ")
def guess(word):
word = word.lower().replace(" ", "_")
hypernym_chain = find_hypernyms(f"{word}.n.01")
print(len(hypernym_chain))
print(hypernym_chain)
third = hypernym_chain[int(len(hypernym_chain) / 4)]
caption = f"The image seems to display a {hyper2text(third)}. Maybe a {hyper2text(hypernym_chain[0])}?"
return caption
print(guess(sys.argv[-1]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment