def __init__(self): # QuickTime - MacOS has record feature for phone (best) self.use_quicktime = False self.use_input = False # the filename of the image (no extension = capturing image) self.picture = 'source' # location of where to work on self.picture self.location = os.getcwd() # Replace with your own auth file name self.google_auth_json = 'HQproject-a1a4e25e4b45.json' # wikipedia setting (english) self.wiki = wikipediaapi.Wikipedia('en') self.vb = Vocabulary() # The OCR text (directly converted from image) self.raw = '' # processed texts self.question = '' self.question_nouns = '' self.answers = {} self.lookup_info = {} # For debugging self.times = {} self.verbose = False
def __init__(self): # This determines source location on where to caputer picture # QuickTime - MacOS has record feature for phone (best) # WebCam - Use OpenCV to capture photo (untested) self.use_quicktime = False self.use_webcam = False self.use_input = False # The filename of picture (no extension means we're capturing image) self.picture = 'source' # Default location of where to work on self.picture self.location = os.getcwd() # Replace with your own auth file name self.google_auth_json = 'blissend.json' # Default the language for wikipedia searches self.wiki = wikipediaapi.Wikipedia('en') self.vb = Vocabulary() # The OCR text self.raw = '' # The information we ultimately wanted to be analyzed self.question = '' self.answers = {} self.definitions = {} # For debugging self.verbose = False
def labels(self, query): """ return parsed result """ res = [] meanings = vb.meaning(query, format="list") if meanings: meanings = [ e.replace("<i>", "").replace("</i>", "").replace("[i]", "").replace("[/i]", "") for e in meanings ] for e in meanings: res.append((query, "meaning", e)) synonyms = vb.synonym(query, format="list") if synonyms: for e in synonyms: res.append((query, "synonym", e)) antonyms = vb.antonym(query, format="list") if antonyms: for e in antonyms: res.append((query, "antonym", e)) #ps = vb.part_of_speech(query, format="list") #if ps: # for e in ps: # res.append((query, "part_of_speech", e)) examples = vb.usage_example(query, format="list") if examples: for e in examples: res.append((query, "usage_example", e)) return res
def query(self, query): """ return raw result (dict) """ cons = { "meaning": [], "synonym": [], "antonym": [], "usage_example": [], "part of speech": [] } meanings = vb.meaning(query, format="list") if meanings: cons["meaning"] = [ e.replace("<i>", "").replace("</i>", "").replace("[i]", "").replace("[/i]", "") for e in meanings ] synonyms = vb.synonym(query, format="list") if synonyms: cons["synonym"] = synonyms antonyms = vb.antonym(query, format="list") if antonyms: cons["antonym"] = antonyms ps = vb.part_of_speech(query, format="list") if ps: cons["part of speech"] = ps examples = vb.usage_example(query, format="list") if examples: cons["usage_example"] = [ e.replace("[", "").replace("]", "") for e in examples ] return cons
def meaning(self, word): definition = 'DEFINITION: ' word_meaning = vb.meaning(word, format="list") if not word_meaning: return False definition += vb.meaning(word, format="list")[0] definition = self.statement(definition) definition += self.addLine() return definition
def dictonarySynonums(self, word): synJSON = vb.synonym(word) if synJSON != False: synonyms_lists = [ dictSyno["text"].encode('ascii', 'ignore') for dictSyno in json.loads(vb.synonym(word)) ] return set(synonyms_lists) else: return set([])
def wordApplications(mess): if mess.find("soph") == 0 and ("define" in mess or "definition" in mess or "meaning" in mess) or mess.find("define") == 0: word = getWord(mess) if word == None: return else: result = str(d.meaning(word)) resultF = meaningParser(result) return ("***" + str(word).upper() + "*** meaning(s)" + str(resultF)) elif mess.find("soph") == 0 and ("antonym" in mess or "opposite" in mess or "different" in mess and "word" in mess) or mess.find("antonym") == 0: word = getWord(mess) if word == None: return else: result = str(v.antonym(word)) resultF = parser(result) if resultF == None or resultF == "1. ": return ("Couldn't find any :(") return ("**" + str(word) + "** antonym(s)\n" + str(resultF)) elif mess.find("soph") == 0 and ("synonym" in mess or "similar to" in mess and "word" in mess) or mess.find("synonym") == 0: word = getWord(mess) if word == None: return else: result = str(v.synonym(word)) resultF = parser(result) if resultF == None or resultF == "1. ": return ("Couldn't find any :(") return ("**" + str(word) + "** synonym(s)\n" + str(resultF)) mess = mess[:mess.find("d") + 1] revmess = mess[::-1] if revmess.find("drow") == 0 and mess.find( "soph") == 0 and " is " in mess and " a " in mess: word = mess[mess.find(" is ") + 4:mess.find(" a ")] if d.meaning(word) == None: return ("Well, it's not in my dictionary... :(") else: return ("Yeah, it is! :D")
def test_translate_found(self, mock_api_call): res = { "tuc": [{ "phrase": { "text": "anglais", "language": "fr" } }, { "phrase": { "text": "germanique", "language": "fr" }, }] } mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res expected_result = '[{"text": "anglais", "seq": 0}, {"text": "germanique", "seq": 1}]' expected_result = json.dumps(json.loads(expected_result)) result = vb.translate("english", "en", "fr") if sys.version_info[:2] <= (2, 7): self.assertItemsEqual(expected_result, result) else: self.assertCountEqual(expected_result, result)
def test_synonynm_found(self, mock_api_call): res = { "tuc": [{ "phrase": { "text": "get angry", "language": "en" } }, { "phrase": { "text": "mad", "language": "en" }, }] } mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res expected_result = '[{"text": "get angry", "seq": 0}, {"text": "mad", "seq": 1}]' expected_result = json.dumps(json.loads(expected_result)) result = vb.synonym("angry") if sys.version_info[:2] <= (2, 7): self.assertItemsEqual(expected_result, result) else: self.assertCountEqual(expected_result, result)
def run_bot(reddit): print ("Running...") word = (pick_word()).lower() deff = vb.meaning(word, format = "list") if deff is False or len(word) < config.minimum or len(word) > config.maximum: use_word(word, unused_words, used_words) deff = [] print ("Could not find deffinition/didnt meet length requirements of '" + word.title() + "'. Finding another...") run_bot(reddit) else: print ("Found deffinition for '" + word.title() + "'. Posting...") string = "# Word of the day: " + word.title() for i in range(len(deff)): if i < config.ammount: string += "\n\n" string += str(i + 1) string += ": " reFormattedString = re.sub(r"\<.\>", "", deff[i]) reFormattedString1 = re.sub(r"\[.\]", "", reFormattedString) reFormattedString2 = re.sub(r"\</.\>", "", reFormattedString1) reFormattedString3 = re.sub(r"\[/.\]", "", reFormattedString2) string += reFormattedString3 i += 1 string += config.message submitted = reddit.subreddit(config.subreddit).submit("Word Of The Day - " + now.strftime("%B %d, %Y") + " - " + word.title(), string) if config.distinguish is True and config.sticky is False and config.moderator is True: submitted.mod.distinguish() elif config.sticky is True and config.moderator is True: submitted.mod.sticky() print ("Posted Successfully!") use_word(word, unused_words, used_words) print ("Next: " + str(unused_words[0]).title()) print ("Waiting till " + config.time + "...")
def getDef(word): dictionary = PyDictionary() definition = dictionary.meaning(word) if isinstance(definition, dict) and 'Noun' in definition: defs = definition['Noun'] if isinstance(defs, list) and len(defs) > 0: return defs # wordnik dictionary wordApi = WordApi.WordApi(client) definitions = (wordApi.getDefinitions(word, partOfSpeech='noun', limit=3)) if definitions is not None and len(definitions) > 0: return [(definition.text).lower() for definition in definitions] meaningsList = vocabulary.meaning(word) if meaningsList != False: defs = json.loads(meaningsList) if (len(defs) > 0): definitions = [] for definition in defs: if definition['text']: d = re.sub('<[^<]+?>', '', definition['text']) definitions.append(d.lower()) if len(definitions) > 0: return definitions # owlbot api url = 'https://owlbot.info/api/v2/dictionary/' + word r = requests.get(url) if r is not None: try: result = r.json() if len(result) > 0: definitions = [] for item in result: if (item['type'] == 'noun' and item['definition']): definitions.append(item['definition'].lower()) if len(definitions) > 0: return definitions except: pass # wiktionary try: parser = WiktionaryParser() result = parser.fetch(word) if result is not None: definition = result[0]['definitions'] if definition and len(definition) > 0: definition = definition[0] if 'partOfSpeech' in definition: if definition['partOfSpeech'] == 'noun': defs = definition['text'].lower().split('\n') if len(defs) > 1: return defs[0:2] elif len(defs) == 1: return defs except: return ' ' return ' '
def test_synonynm_empty_list(self, mock_api_call): res = {"result": "ok", "tuc": [], "phrase": "angry"} mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res self.assertFalse(vb.synonym("angry"))
def test_translate_empty_list(self, mock_api_call): res = {"result": "ok", "tuc": [], "phrase": "english"} mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res self.assertFalse(vb.translate("english", "en", "fr"))
def test_antonym_ant_key_error(self, mock_api_call): res = {"noun": {}, "verb": {}} mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res self.assertFalse(vb.antonym("love"))
def get_classification(word): full_meaning = vb.part_of_speech(word, format='dict') classification = None if full_meaning: classification = full_meaning[0]['text'] if classification is None: classification = '' return classification
def validateWordThoroughly(word): partOfSpeech = vb.part_of_speech(word) # Hack: If a part of speech was found, then we know this is a valid word. # TODO - add a check here to remove words that invalid by my family's # rules (i.e. proper nouns) if (partOfSpeech): return True return False
def get_dictionary(subject): cons = {"meaning": [], "synonym": [], "antonym": [], "example": [], "part of speech": []} meanings = vb.meaning(subject, format="list") if meanings: cons["meaning"] = [e.replace("<i>", "").replace("</i>", "").replace("[i]", "") .replace("[/i]", "") for e in meanings] synonyms = vb.synonym(subject, format="list") if synonyms: cons["synonym"] = synonyms antonyms = vb.antonym(subject, format="list") if antonyms: cons["antonym"] = antonyms ps = vb.part_of_speech(subject, format="list") if ps: cons["part of speech"] = ps examples = vb.usage_example(subject, format="list") if examples: cons["example"] = [e.replace("[", "").replace("]", "") for e in examples] return cons
def antonyms(dict): list_of_words, a = [], [] antonyms = {} for value in dict.values(): list_of_words.append(value) list_of_words.sort() for i in range(-1, -30, -1): for key in dict.keys(): if dict[key] == list_of_words[i]: a.append(key) for elem in a: if vb.antonym(elem) != False: antonyms[elem] = [] antonyms[elem].append(vb.antonym(elem, format='list')) for k, v in antonyms.items(): print(f'Antonym for {k.upper()} is {v} ')
def antonym(self, word): res = 'ANTONYMS: ' antonyms = vb.antonym(word, format="list") if not antonyms: return False res += antonyms[0] res += self.more(antonyms[1:]) res += self.addLine() return res
def synonym(self, word): res = 'SYNONYMS: ' synonyms = vb.synonym(word, format="list") if not synonyms: return False res += synonyms[0] res += self.more(synonyms[1:]) res += self.addLine() return res
def get_syn(x): word = x.split() syns = [] for ii in range(0, len(word)): s = vb.synonym(word[ii], format='list') if s: if s[0] not in syns: syns.append(s[0]) return syns
def definition(text, lang='en-en'): src, dest = lang.split('-') response = voc.meaning(text, src, dest) if not response or response == '[]': return '' response = json.loads(response) output = "" for i, a in enumerate(response, start=1): output += str(i) + '. ' + a['text'] + '\n' return output
async def translate(bot,msg): try: print('GET /translate') with msg['text'].split() as text: source = text[1] dest = text[2] word = text[3] await bot.sendMessage(msg['chat']['id'],eval(vb.translate(word,source_lang=source,dest_lang=dest))[0]['text']) except: await bot.sendMessage(msg['chat']['id'],"Syntax: /translate sourceLang destLang words. Eg: /translate en zh car")
def parse_keyword_synonym(self, tokens): synonyms = [] for token in tokens: try: data = json.loads(vb.synonym(token))[0:self.synonym_limit] for word_txt in data: synonyms.append(word_txt["text"]) except: continue return synonyms
def test_meaning_key_error(self, mock_api_call): res = {"result": "ok", "phrase": "humming"} mock_api_call.return_value = mock.Mock() mock_api_call.return_value.status_code = 200 mock_api_call.return_value.json.return_value = res expected_result = '[{"seq": 0, "text": "the act of singing with closed lips"}]' expected_result = json.dumps(json.loads(expected_result)) self.assertFalse(vb.meaning("humming"))
def synonym(text, lang='en-en'): # do not support russian src, dest = lang.split('-') response = voc.synonym(text, src, dest) if not response or response == '[]': return '' response = json.loads(response) output = "" for i, a in enumerate(response, start=1): output += '\t' + str(i) + '. ' + a['text'] + '\n' return output
def synonym(word): syn = vb.synonym(word) if (syn == False): return "No Synonyms Founds" syns = json.loads(syn) ret = "Synonyms are " i = 0 while (i < 4 and i < len(syns)): ret += syns[i]['text'] + ", " i += 1 ret = ret[:-2] return ret
def antonym(word): ant = vb.antonym(word) if (ant == False): return "No Antonyms Found" ants = json.loads(ant) ret = "Antonyms are " i = 0 while (i < 4 and i < len(ants)): ret += ants[i]['text'] + ", " i += 1 ret = ret[:-2] return ret
def details(word): meaning = vb.meaning(word) antonym = vb.antonym(word) synonym = vb.synonym(word) usage = vb.usage_example(word) if meaning == False: meaning = 'Not Found' else: meaning = json.loads(meaning) # meaning = str(meaning[0]['text']) meaning = [unescape(meaning[i]['text']) for i in range(len(meaning))] if antonym == False: antonym = 'Not Found' else: antonym = json.loads(antonym) antonym = str(antonym[0]['text']) if synonym == False: synonym = 'Not Found' else: synonym = json.loads(synonym) synonym = str(synonym[0]['text']) if usage == False: usage = 'Not Found' else: usage = json.loads(usage) usage = str(usage[-1]['text']) values = { 'meaning': meaning, 'antonym': antonym, 'synonym': synonym, 'usage': usage } return values
def define_word(word): definitions = vb.meaning(word) if (definitions is None): return "Word not found" else: worddefs = json.loads(definitions) ret = word + ": " i = 0 while (i < 4 and i < len(worddefs)): ret += str(i + 1) + ". " + worddefs[i]['text'] + "; " i += 1 ret = ret[:-2] return ret