def translate(token, dictionary, expanded_sample, babelnet_parameters=None): if babelnet_parameters is None: translation = dictionary.translate(token) else: translation = dictionary.translate(token, babelnet_parameters) if translation not in expanded_sample: expanded_sample.append(translation)
def test_answer(): testdict = { 'a': 'b', 'c': 'd', } assert translate('a', testdict) == 'b' assert translate('b', testdict) == 'a'
def interpret(labeled_words): with codecs.open('src/data/lidinsky.txt', 'r', encoding='utf-8') as f: data = f.read() for line in data.splitlines(): # split a line words = re.split('\s|:\s|,\s', line) # translate it words = list((dictionary.translate(word) for word in words)) # label it labeled = list() for word in words: label = list() if name.is_given_name(word): label.append('GIVEN_NAME') if name.is_family_name(word): label.append('FAMILY_NAME') if place.is_parish_name(word): label.append('PARISH') if re.search('([1-3][0-9]|[1-9])\.([1-2][0-9]|[1-9])\.([1-2][0-9]{3})', word): label.append('DATE') if word in KEYWORDS: label.append('KEYWORD') if re.search('^[0-9]+$', word): label.append('NUMBER') if re.search('^\[.*\]$', word): label.append('REFERENCE') if job.is_job(word): label.append('JOB') if word in RELATIONSHIPS: label.append('RELATIONSHIP') if len(label) != 1: print(word, label)
def __init__(self, d={}, mode=0, invisible_fields=[], editable_fields=[], parent=None): super().__init__(parent) layout = QGridLayout() self.setLayout(layout) self.d = d self.d_bakup = copy.copy(d) self.widgets = [] i = 0 for k, v in d.items(): if k in invisible_fields: continue is_editable = k in editable_fields is_desc = not (k == 'desc' or k == 'event_desc') w = LineEditDesc([str(k), translate(k)], str(v), is_desc, is_editable and mode) self.widgets.append(w) layout.addWidget(w, i, 0, 1, 1) i = i + 1
def uspeak(lang, use_sounds): notify = Notification('USpeak') r = sr.Recognizer(language=lang) with sr.Microphone() as source: with reduced_volume(): if use_sounds: say.run('go') notify.show('Waiting for voice command...', NOTIFY_TYPE.OK, NOTIFY_LEVEL.CRITICAL) try: audio = r.listen(source, timeout=3) except TimeoutError: notify.show('Sorry, could not hear your voice', notify_type=NOTIFY_TYPE.ERROR) return notify.show('Working on it...', NOTIFY_TYPE.MIC, NOTIFY_LEVEL.CRITICAL) try: recognized_text = r.recognize(audio) except LookupError: notify.show('Could not understand your phrase, try again please', notify_type=NOTIFY_TYPE.ERROR) return command = translate(recognized_text, dictionary=read_dictionary(language=lang)) if command: notify.show('Executing: {}.\nReady for another command.'.format(command), notify_type=NOTIFY_TYPE.OK) if run_command(command, lang): notify.show('Sorry, there were some problems running your command.', notify_type=NOTIFY_TYPE.ERROR) else: notify.show('Unknown command: {}'.format(recognized_text), notify_type=NOTIFY_TYPE.ERROR)
def save_press(self): #sender = self.sender() people = {} for e in self.buttext: people[translate(e[0].text())] = e[1].text() people['desc'] = self.desc.toPlainText() print(self.edit_people(people)) self.db.peoples.save() self.close()
def download_translations(self, source, language, text, unit, user): """Return tuple with translations.""" for t in dictionary.translate(text): yield { "text": t, "quality": 100, "service": self.name, "source": text }
def download_translations( self, source, language, text: str, unit, user, search: bool, threshold: int = 75, ): """Return tuple with translations.""" for t in dictionary.translate(text): yield {"text": t, "quality": 100, "service": self.name, "source": text}
def program_execution(): quit_program = False while not quit_program: output = translate() exit_question = input( "Would you like to know another word? Press Q to quit or another key to continue. " ) if exit_question == "": continue elif exit_question[0].lower() == "q": print("Bye!") quit_program = True else: continue
def uspeak(lang, use_sounds): notify = Notification('USpeak') r = sr.Recognizer(language=lang) with sr.Microphone() as source: with reduced_volume(): if use_sounds: say.run('go') notify.show('Waiting for voice command...', NOTIFY_TYPE.OK, NOTIFY_LEVEL.CRITICAL) try: audio = r.listen(source, timeout=3) except TimeoutError: notify.show('Sorry, could not hear your voice', notify_type=NOTIFY_TYPE.ERROR) return notify.show('Working on it...', NOTIFY_TYPE.MIC, NOTIFY_LEVEL.CRITICAL) try: recognized_text = r.recognize(audio) except LookupError: notify.show('Could not understand your phrase, try again please', notify_type=NOTIFY_TYPE.ERROR) return command = translate(recognized_text, dictionary=read_dictionary(language=lang)) if command: notify.show( 'Executing: {}.\nReady for another command.'.format(command), notify_type=NOTIFY_TYPE.OK) if run_command(command, lang): notify.show( 'Sorry, there were some problems running your command.', notify_type=NOTIFY_TYPE.ERROR) else: notify.show('Unknown command: {}'.format(recognized_text), notify_type=NOTIFY_TYPE.ERROR)
def download_translations(self, language, text, unit, request): """ Returns tuple with translations. """ return [(t, 100, self.name, text) for t in dictionary.translate(text)]
from entities import * import dictionary as dic from generators import * date = 0 language = randomLanguage() location = Location('home', 1000, 'CCf', 100) player = Person('Name', 25, 'M', language, {}, location) print(f'you are with your kinfolk at {player.location.name}') #print(language.__dict__) text = dic.translate(f'you be with your human at {player.location.name}', language) print(text) #print(dic.read_xsampa(text)) #print(language.words) # 2ndPerson be LOCATION locative KIN comitative # 2ndPerrsonPossesive how to do cases generatively? # just gonna hardcode for now
def download_translations(self, source, language, text, unit, user): """Return tuple with translations.""" return [(t, 100, self.name, text) for t in dictionary.translate(text)]
def __init__(self, people=0, db=0, mode=0): super().__init__() self.font = mainfont self.resize(700, self.height()) layout = QGridLayout() self.buttext = [] self.db = db self.people = people #print(people) self.pid = self.people['pid'] self.edit_people = db.edit_people self.mode = mode self.gallery = Gallery(self.pid, self.db, mode) self.docviewer = DocViewer(self.pid, self.db, self.mode) #self.photos = self.gallery.curpixmap #print(self.photos) self.photo = QPushButton() if self.gallery.curpixmap: self.pixmap = QPixmap(self.gallery.curpixmap) #self.photofile = self.photo else: self.pixmap = QPixmap(os.path.join('images', 'f.png')) self.change_icon() self.photo.clicked.connect(self.show_photo) self.docs = QPushButton() if self.docviewer.docs_ids and type(self.docviewer.docs_ids) == type( []) and len(self.docviewer.docs_ids) > 0: self.docs_pixmap = QPixmap(os.path.join('images', 'docs.jpg')) else: self.docs_pixmap = QPixmap( os.path.join('images', 'empty_folder.png')) self.docs.setIcon(self.docs_pixmap) #self.docs.setAlignment(Qt.AlignCenter) self.docs.setIconSize(rect.size()) self.docs.clicked.connect(self.show_docs) self.inb = QInvisibleButton(translate('Описание')) self.inb.setFont(self.font) self.desc = QTextEdit() if mode == 0: self.desc.setReadOnly(True) if 'desc' in people.keys(): self.desc.setPlainText(people['desc']) layout.addWidget(self.photo, 0, 0, len(people.keys()), 1) layout.addWidget(self.docs, len(people.keys()) + 2, 0, 1, 1) layout.addWidget(self.desc, len(people.keys()) + 2, 1, 1, 1) layout.addWidget(self.inb, len(people.keys()) + 2, 1, 1, 1) #layout.addWidget(self.eventList, 0, 2, len(people.keys())+3, 1) i = 0 for k, v in self.people.items(): # if mode == 0: # if json_people.columns[i] == 'date_end' and str(e) == '': # continue # if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and get_pol(data)[0] == 'м': # continue if k == 'desc': continue lb = QInvisibleButton(translate(k)) lb.setFont(self.font) te = QLineEdit(str(v)) te.setFont(self.font) te.setReadOnly(True) self.buttext.append([lb, te]) #if json_people.columns[i] == 'maiden' and len(get_pol(data)) > 0 and get_pol(data)[0] == 'м': # continue layout.addWidget(te, i, 1, 1, 1) layout.addWidget(lb, i, 1, 1, 1) if mode: te.setReadOnly(False) lb.clicked.connect(self.button_pressed) te.editingFinished.connect(self.line_edit_finished) i = i + 1 if (mode == 1) or (mode == 2): bn = QPushButton('Сохранить') bn.setStyleSheet("font-weight: bold; font-size:11pt;") #bn.setFont(self.font) layout.addWidget(bn, len(people.keys()) + 3, 0, 1, 2) #layout.addWidget(bn, 1 , len(json_people.columns) + 1, 1, 1) bn.clicked.connect(self.save_press) self.setLayout(layout)
def get_exchange_id(self): for e in self.buttext: if translate(e[0].text()) == 'id': return e[1].text() return 0
def commands(): while True: query = takeCommand().lower() if 'wikipedia' in query: speak('Searching Wikipedia...') query = query.replace("wikipedia", "") results = wikipedia.summary(query, sentences=2) speak("According to Wikipedia") print(results) speak(results) elif "cpu" in query or "cpu details" in query: cpu() elif 'dictionary' in query: speak('What you want to search in your dictionary?') translate(takeCommand()) elif 'news' in query: speak('okay..') speak_news() speak('Do you want to read the full news...') test = takeCommand() if 'yes' in test: speak('Ok Sir, Opening browser...') webbrowser.open(getNewsUrl()) speak('You can now read the full news from this website.') elif 'open youtube' in query: webbrowser.get('chrome').open("youtube.com") elif 'search youtube' in query: speak('What you want to search on Youtube?') youtube(takeCommand()) elif 'search internet' in query: speak("what should i search on internet") cm = takeCommand().lower() webbrowser.open(f'{cm}') elif 'stackoverflow' in query: webbrowser.get('chrome').open("stackoverflow.com") elif 'github' in query: webbrowser.get('chrome').open("https://github.com/shivasaimereddy") elif 'music' in query: music_dir = 'enter music path' songs = os.listdir(music_dir) rd = random.choice(songs) print(songs) for song in songs: if song.endswith('.mp3'): os.startfile(os.path.join(music_dir, rd)) elif 'search for a location' in query or "location" in query: speak('What is the location?') location = takeCommand() url = 'https://google.nl/maps/place/' + location + '/&' webbrowser.get('chrome').open_new_tab(url) speak('Here is the location ' + location) elif 'remember this' in query or 'remember' in query: speak("Ok, tell me") rememberMessage = takeCommand() speak("you said me "+rememberMessage) remember = open('note.txt', 'w') remember.write(rememberMessage) remember.close() elif 'did you remember anything' in query or 'read data' in query: remember = open('note.txt', 'r') speak("you said me to remember that" + remember.read()) elif 'switch to friday' in query: engine.setProperty('voice', voices[1].id) speak("Hello Sir, I am friday. How may i assist you") elif 'switch to jarvis' in query: engine.setProperty('voice', voices[0].id) speak("Hello Sir, Jarvis is back. How may i assist you?") elif "stop" in query: speak("ok") os.system("taskkill /f /ai music") elif 'time' in query: strTime = datetime.datetime.now().strftime("%I:%M") speak(f"Sir, the time is {strTime}") elif "play song on youtube" in query: kit.playonyt("salt") elif 'open code' in query: codePath = "code.exe path" os.startfile(codePath) elif 'close code' in query: speak("Closing Code") os.system("taskkill /f /im code.exe") elif "ip address" in query: ip = requests.get('https://api.ipify.org').text print(ip) speak(f"your ip address is {ip}") elif "where am i" in query: speak("You have not programmed me that well, ok... let me try ") try: ipAdd = requests.get('https://api.ipify.org').text print(ipAdd) url = 'https://get.geojs.io/v1/ip/geo/'+ipAdd+'.json' geo_requests = requests.get(url) geo_data = geo_requests.json() city = geo_data['city'] country = geo_data['Country'] speak(f'we are in {city} of {country}') except Exception as e: print(e) speak("its difficult for me") speak("I already told you, you have not programmed me that good.") elif "switch desktop" in query: keyDown("alt") press("tab") keyUp("alt") elif "open notepad" in query: npath = "C:\\WINDOWS\\system32\\notepad.exe" os.startfile(npath) elif "close notepad" in query: speak("Closing Notepad") os.system("taskkill /f /im notepad.exe") elif "open command prompt" in query: os.system("start cmd") elif ("shutdown system") in query: speak("Do you want me to turn off laptop") takeCommand() if "yes" in query: os.system("shutdown /s /t 5") else: speak("cool, im not doing that") speak("im listening") takeCommand() elif "restart system" in query: os.system("shitdown /r /t 5") elif "sleep" in query: os.system("rundll32.exe powrprof.dll, SetSuspendState 0,1,0") elif "send email" in query or "send mail" in query: email = "" password = "" speak("enter the email address of the recipient") recipient = input("Enter Email Address: ") speak("What is the subject of the mail") query = takeCommand().lower() subject = query speak("and what is the message") query2 = takeCommand().lower() message = query2 speak("Do you want to attach any file") query3 = takeCommand().lower() if "yes" in query3: speak("Ok, i can help you with that") speak("enter the correct path of file into the shell") file_location = input("Enter path") speak("please wait, im sending the email now") msg = MIMEMultipart() msg['From'] = email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) filename = os.path.basename(file_location) attachment = open(file_location, 'rb') part = MIMEBase('application', 'octet-stream') part.set_payload(attachment.read()) encoders.encode_base64(part) part.add_header('Content-Disposition', "attachment; filename= %s" % filename) msg.attach(part) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, recipient, text) server.quit() speak("email has been sent") else: speak("please wait, im sending email now") msg = MIMEMultipart() msg['From'] = email msg['To'] = recipient msg['Subject'] = subject msg.attach(MIMEText(message, 'plain')) server = smtplib.SMTP('smtp.gmail.com', 587) server.starttls() server.login(email, password) text = msg.as_string() server.sendmail(email, recipient, text) server.quit() speak("email has been sent") elif 'send message' in query or 'message' in query: speak('what should i say') msg = takeCommand() account_sid = '' auth_token = '' client = Client(account_sid, auth_token) message = client.message\ .create( body=msg, from_='', to='' ) print(message.sid) elif "whats app" in query: kit.sendwhatmsg("enter number", "Jarvis test message", 2, 25) elif "volume up" in query: pyautogui.press("volumeup") elif "volume down" in query: pyautogui.press("volumedown") elif "volume mute" in query or "mute" in query: pyautogui.press("volumemute") elif "screenshot" in query: speak("suggest a name for screenshot") name = takeCommand().lower() speak("Ok, just a second") img = pyautogui.screenshot() img.save(f"{name}.png") speak("Screenshot saved in mainframe, Job Done") elif "instagram" in query or "instagram profile" in query: speak("enter username") name = input("enter username") webbrowser.open(f"www.instagram.com/{name}") speak(f"here is the profile of {name}") time.sleep(3) speak("do you want to download this profic picture") condition = takeCommand().lower() if "yes" in condition or "yeah" in condition: try: mod = instaloader.Instaloader() mod.download_profile(name.get(), profile_pic_only=True) speak("Done, image stored in main frame") except Exception as e: print(e) else: speak("I cant do that at the moment") elif "read" in query or "read pdf" in query: pdf_reader() elif "folder actions" in query or "folder" in query or "this folder" in query: speak("what action do you want to perform") condition = takeCommand().lower() if "hide" in condition or "hide all files" in condition: os.system("attrib +h /s /d") speak("all the files are now hidden") elif "visible" in condition or "make all files visible" in condition: os.system("attrib -h /s /d") speak("all files are now visible") elif "leave for now" in condition: speak("cool") elif "hide all files" in query: os.system("attrib +h /s /d") speak("all the files are now hidden") elif "make all files visible" in query: os.system("attrib -h /s /d") speak("all files are now visible") elif 'jarvis are you there' in query: speak('yes sir, at your service') elif 'who are you' in query: speak('im jarvis, Just A Rather Very Intelligent System. i can perform some basic desktop actions that can make your work simple') elif 'what can you do' in query: speak('ask me something, you will get to know, what i can do.') elif 'internet speed' in query or 'check internet speed' in query: st = speedtest.Speedtest() dl = st.download() up = st.upload() speak( f'we have {dl} bits per second download speed and {up} bits per second upload speed') elif 'see you later' in query or 'bye' in query: speak("Im signing off, have a good day") exit()
engine.say("Tere " + part_of_day + " , " + person + " !") engine.runAndWait() while person != None: window6.close() window = createwindow4() window.Maximize() event, values = window.read() if event == "Sulge rakendus" or event == sg.WIN_CLOSED: break elif event == "Ilmateade": initial_weather = get_weather() temperature = initial_weather[0] initial = initial_weather[1] wind = initial_weather[2] description = translate(initial) weather = ("Temperatuur on: " + str(temperature) + "°C" + "\n" + "Tuule kiirus on: " + str(wind) + "m/s." + "\n" + "Olustik: " + description + ".") window.close() window2 = createwindow2(weather) window2.Maximize() event, values = window2.read() if event == "Sulge rakendus" or event == sg.WIN_CLOSED: break elif event == "Tagasi": window2.close() continue elif event == "Sündmused": events = display_schedule(person) window.close()
def headerData(self, section, orientation, role=Qt.DisplayRole): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return translate( self.columns_names[section] ) #('Font family') if section == 0 else ('Embedded') return QAbstractTableModel.headerData(self, section, orientation, role)
def parse_age(text): match = re.search('([0-9]+)\s+(\S+)', text) if match: if dictionary.translate(match.group(2)) == 'years': return 'age', int(match.group(1))
import dictionary # this is the script that calls the dictionary and translates the lines in the file given into the languages specified # the original lines and resulting translations are stored in the file called inputLanguage+outputLanguage+Translation.txt # ex. EnFrTranslation.txt inputFile = raw_input("Please enter the name of an input file: ") originalWords = open(inputFile, 'r').read().split("\n")[:-1] inputLanguage = raw_input("Please enter the name of the input language: ") outputLanguage = raw_input("Please enter the name of the output language: ") translationsFile = open(inputLanguage.capitalize()+outputLanguage.capitalize()+"Translation.txt",'w') i = 1 for word in originalWords: translationsFile.write(str(i)+' '+dictionary.translate(word, inputLanguage, outputLanguage) + "\n") i+=1 translationsFile.close()
def pushButton_slot(self): to_search = self.textEdit.toPlainText() result = dictionary.translate(to_search) self.output.setText(result)
def download_translations(self, source, language, text, unit, user): """Return tuple with translations.""" return [ {'text': t, 'quality': 100, 'service': self.name, 'source': text} for t in dictionary.translate(text) ]
def test_not_found(): testdict = {} with pytest.raises(ValueError): assert translate('f', testdict) == 'b'
def download_translations(self, source, language, text, unit, user): ''' Returns tuple with translations. ''' return [(t, 100, self.name, text) for t in dictionary.translate(text)]
import dictionary as dic #import setting_synth from battle import * from number_base import * import place, entities import display from generators import * gameState = 1 pause = True event_log = [] pop = 5 town = Location('town', 500, pop) fillLocation(town) language = randomLanguage() #print(language.vowels, language.consonants) #print(language.words) print(dic.translate('human drink 20 water', language)) #print(town.name, town.list) #town.census()
def download_translations(self, language, text, unit): ''' Returns tuple with translations. ''' return [(t, 100, self.name, text) for t in dictionary.translate(text)]
def __init__(self,text): self.text = text info = dictionary.translate(text) self.part = info['partOfSpeech'] self.translations = info['translations']