Created
January 18, 2024 09:05
-
-
Save tarekziade/32eeadc114897fcd043e1616ed087577 to your computer and use it in GitHub Desktop.
imagenet_hypernyms.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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