예제 #1
0
파일: main.py 프로젝트: twitchat/Kalpha
def googletalk(lan, msg):
    if lan == "tw":
        try:
            tts = gTTS(text=msg, lang="zh-tw")            
            tts.save("message.mp3")
        except:
            return 0
    if lan == "en":
        try:
            tts = gTTS(text=msg, lang="en")            
            tts.save("message.mp3")
        except:
            print "en error"
            return 0
    if lan == "jp":
        try:
            tts = gTTS(text=msg, lang="ja")            
            tts.save("message.mp3")
        except:
            print "en error"
            return 0
    filename = "message.mp3"
    clip = mp3play.load(filename)
    
    clip.play()
    time.sleep(min(15, clip.seconds()))
    clip.stop()
예제 #2
0
파일: Main.py 프로젝트: RyanEder/MavisPy
    def GetForecast(self, day):
        if self.PopulateWeather():
            temp = self.weather.split('<time-layout time-coordinate="local"')[1].split('</layout-key>')[1].strip().split('</time-layout>')[0].strip().split('\n')
            sprites = [i.split('period-name=')[1].split('>')[0].split('"')[1].lower() for i in temp]
            self.tomorrow = sprites[2]
            temp = self.weather.split('<name>Text Forecast</name>')[1].strip().split('</wordedForecast>')[0].strip().split('\n')
            text_forecasts = [i.split('<text>')[1].strip().split('</text>')[0].strip().lower() for i in temp]
            if not len(sprites) == len(text_forecasts):
                self.audio.Speak(gTTS("I had a hard time retrieving the forecasts, try again later", lang='en'), 4)
                return

            self.forecast = {}
            for i in range(len(sprites)):
                self.forecast[sprites[i]] = text_forecasts[i]
        if not day in self.forecast:
            if day == 'this afternoon':
                day = 'tonight'
            elif day == 'tomorrow':
                day = self.tomorrow
            elif day == 'tomorrow night':
                day = self.tomorrow + ' night'

        if day in self.forecast:
            self.audio.Speak(gTTS(day + ", " + self.forecast[day], lang='en'), 7)
        else:
            self.audio.Speak(gTTS("I had a hard time retrieving the forecast for " + day, lang='en'), 4)
예제 #3
0
 def validate_connection(self, tts):
     try:
         gTTS(text='Hi').save(tts.filename)
     except:
         raise Exception(
             'GoogleTTS server could not be verified. Please check your '
             'internet connection.')
예제 #4
0
 def do_GET(self):
     quoted_text = self.path[1:]
     text = urllib.parse.unquote(quoted_text)
     sound_path = os.path.join(SOUND_DIR, '%s.mp3' % text)
     if os.path.exists(sound_path) is False:
         gtts.gTTS(text=text, lang='fr').save(sound_path)
     sonos.play_uri('%s/%s.mp3' % (SCORES_URI, quoted_text))
     self.send_response(200)
예제 #5
0
파일: mqtt_speak.py 프로젝트: FredThx/FSTA
	def speak(self, text):
		'''Speak the text
		'''
		try:
			gTTS(text=text, lang=self.language).save("tts.mp3")
			os.system('mpg123 tts.mp3')
			logging.info("'%s' speaked with gTTS."%(text))
		except Exception as e:
			logging.warning(e.message)
예제 #6
0
파일: voice.py 프로젝트: drbeat/Abb1t
 def run(self):
     while 1: 
         msg=self.queue_in.get() # get() is blocking
         chat_id=msg.get_chat_id()
         if msg.get_text()[:len("/voice")]=="/voice" and len(msg.get_text().split(" "))>=2:
             tts=msg.get_text().split(" ",1)[1].lower().replace("Ä","ae").replace("ä","ae").replace("Ü","ue").replace("ü","ue").replace("Ö","oe").replace("ö","oe").replace("ß","ss")
             with tempfile.TemporaryFile() as temporaryfile:
                 gtts.gTTS(text=tts,lang="de").write_to_fp(temporaryfile)
                 temporaryfile.seek(0)
                 self.bot.sendAudio(chat_id,temporaryfile,title="Abb1tvoice")
def main():
    tts = gTTS(text='Hello', lang='en', slow=True)
    tts.save("hello.mp3")

    # 快音
    tts = gTTS(text='Hello', lang='en', slow=False)
    tts.save("hello2.mp3")

    tts = gTTS(text='我是中国人,我深深爱着我的祖国和人民;', lang='zh-cn', slow=False)
    tts.save("hello3.mp3")
예제 #8
0
파일: speaker.py 프로젝트: FredThx/FSTA
	def speak(self, text):
		'''Speak the text
		'''
		#TODO : faire mieux (en paralele gTTS et mpg123
		for text in text.split('.'):
			try:
				gTTS(text=text, lang=self.language).save(self.tmp)
				os.system('mpg123 %s'%(self.tmp))
				logging.info("'%s' speaked with gTTS."%(text))
			except Exception as e:
				logging.warning(e.message)
예제 #9
0
파일: Speech.py 프로젝트: chenbh/Assistant
 def speak (self, text):
     if self.mute:
         print "[mute spoke]" + text
         return
     f = tempfile.TemporaryFile (mode = "wb+")
     start = f.tell ()
     gtts.gTTS (text, lang = 'en').write_to_fp (f)
     f.seek (start)
     pygame.mixer.music.load (f)
     pygame.mixer.music.play ()
     while pygame.mixer.music.get_busy () == True:
         continue
     f.close ()
     print "[Spoke] " + text
예제 #10
0
def speak(voicedata, num):
    print(str((newsnum+1) - num))
    tts = gTTS(text=voicedata, lang='hi')
    tts.save("E:\SandBox\Python\eradioJockey/temp/"+str(num+1)+".mp3")
    shutil.copy('E:\SandBox\Python\eradioJockey\\assets\\alert.wav', 'temp')
    newname = "ren E:\SandBox\Python\eradioJockey\\temp\\alert.wav"+' '+str(num)+'a'+'.wav'
    os.system(newname)
예제 #11
0
파일: TIAg.py 프로젝트: rayoelperro/TIA
def decir(texto):
    try:
        tts = gTTS(text=texto, lang='es-es')
        tts.save("TIAPLAY.mp3")
        os.system("python TIAs.py")
    except:
        print "Error"
예제 #12
0
def createExampleAudioFromTTS(example_sentense):
    time.sleep(3)
    print "creating example audio for "+example_sentense
    tts = gTTS(text=example_sentense, lang='en')
    absolutePathAudio=output_audio_directory+removeSpecialCharacters(example_sentense[:20].encode('utf8'))+".mp3"
    tts.save(absolutePathAudio)
    return absolutePathAudio
예제 #13
0
	def run(self):

        
                filename = 'Phrase1.mp3'

                if self._text in "1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 bonjour pas":
                        filename = "/home/poppy/resources/audio/tts/" + self._text + ".mp3"

                else:
                        tts = gTTS((self._text), lang='fr')
                        tts.save(filename)

                #clip = mp3play.load(os.path.abspath('../utils/Phrase1.mp3'))
                #clip.play()

                #while clip.isplaying() is not False:
                #    time.sleep(0.5)

                pygame.mixer.init(16000)
                pygame.mixer.music.load(os.path.abspath(filename))
                pygame.mixer.music.set_volume(0.5)
                pygame.mixer.music.play()
                
                while pygame.mixer.music.get_busy():
                    time.sleep(0.5)
예제 #14
0
def command_voice(m):
    cid = m.chat.id 
    token = m.text.split(" ", 1)[1]
    tts = gTTS(text=token, lang='es')
    tts.save("tts.mp3")
    audio = open('tts.mp3', 'rb')
    bot.send_audio(cid, audio)
예제 #15
0
def speak(phrase, cache=False, filename='default', show_text=True):
    """
    Speaks a given text phrase
    
    :param phrase: text string to speak
    :param cache: if True, store .mp3 in 'media/responses'
    :raises HTTPError: if Google TTS fails to respond
    """
    if show_text:
        print('\n~ '+phrase+'\n')
    if not settings.USE_TTS:
        print('SPOKEN:', phrase)
        return
    
    try:
        phrase = phrase[:settings.MAX_CHAR]
        tts = gTTS(text=phrase, lang=settings.LANG)
        
        if not cache:
            with tempfile.NamedTemporaryFile(mode='wb', suffix='.mp3', delete=False) as f:
                (temp_path, temp_name) = os.path.split(f.name)
                tts.write_to_fp(f)
            
            play_mp3(temp_name, temp_path)
            os.remove(os.path.join(temp_path, temp_name))
        else:
            filename = os.path.join(settings.RESPONSES_DIR, filename+'.mp3')
            tts.save(filename)
            print('\n~ Saved to:', filename)
            
    except HTTPError as e:
        print('Google TTS might not be updated:', e)
    except Exception as e:
        print('Unknown Google TTS issue:', e)
예제 #16
0
def speak(say):
    print("GENERATING VOICE")
    tts = gTTS(text=say, lang='en')
    tts.save("voice/temp/temp.mp3")
    voice = "runuser -l pi -c 'cvlc --play-and-exit /home/pi/computer/voice/temp/temp.mp3 &' "
    subprocess.call(voice, shell=True)
    return
예제 #17
0
파일: Chester.py 프로젝트: sabo/chester
def main():
    form = HumanLove(name = "APPRECIATE")
    stp = []
    for (s, msgs) in db.iteritems():
        if msgs == []:
            # Let's make sure everyone gets at least one.
            stp.append(s)
    if stp == []:
        # Everyone has at least one message? Cool.
        stp = db.keys()
    form.to.choices = [(s, s) for s in set(stp)]
    if form.validate_on_submit():
        to = form.to.data
        fro = form.fro.data
        # Get a random greeting.
        greet = greetings[random.randrange(len(greetings))].format(to)
        # Get a random farewell
        farewell = signoff[random.randrange(len(signoff))].format(fro)
        full_message = "{} {} {}".format(greet, form.message.data, farewell)
        tts = gTTS(text = full_message)
        messages = db.get(to, [])
        if messages is None:
            messages = []
        db[to] = messages.append(full_message)
        tts.save("messages/message-to-{}-from-{}.mp3".format(to, fro))
        dbf = open("love.pdb", "a+")
        pickle.dump(db, dbf)
        dbf.close()
        return redirect("/")
    return render_template('index.html', form = form)
예제 #18
0
	def __init__(self, task_string, time_string):

		print "Starting"

		self.time_string_list = time_string.split(":")

		self.alarmHour=self.time_string_list[0]
		self.alarmMinute=self.time_string_list[1]

		#to uniquely identify the audio file
		self.alarmID = self.alarmHour+"-"+self.alarmMinute

		#add greeting to text string
		task_string="Hey, time to "+task_string

		#create speech to say when alarm goes off
		tts = gTTS(text = task_string, lang="en")

		self.audio_file_name = "alarm_"+self.alarmID+".mp3"

		#save the audio file
		tts.save(self.audio_file_name)

		#start a thread monitoring for when it goes off
		self.monitorThread = Thread(target=self.monitorAlarm)
		self.hasntGoneOff = True
		self.monitorThread.start()
예제 #19
0
def make_tts_file(content, lang):
    fp = mktemp()

    tts = gTTS(text=content, lang=lang)
    tts.save(fp)

    return fp
예제 #20
0
def text_to_speech():

    s = textPad.get('1.0', textPad.index(INSERT))

    try:
        tts = gTTS(text=s, lang='en')

    except:
        tkinter.messagebox.showinfo("Error", "An error occured make sure you have connected to internet!!")

    try:
        tts.save("temp.mp3")
        mixer.init()
        mixer.music.load("temp.mp3")
        mixer.music.play()

        try:
            os.remove("temp2.mp3")

        except:
            pass

    except:
        tts.save("temp2.mp3")
        mixer.music.load("temp2.mp3")
        mixer.music.play()
        os.remove("temp.mp3")
예제 #21
0
파일: google.py 프로젝트: chakraroy/talkey
 def _say(self, phrase, language, voice, voiceinfo, options):
     tts = gtts.gTTS(text=phrase, lang=voice)
     with tempfile.NamedTemporaryFile(suffix='.mp3', delete=False) as f:
         tmpfile = f.name
     tts.save(tmpfile)
     self.play(tmpfile, translate=True)
     os.remove(tmpfile)
예제 #22
0
 def speak(self, s):
     """
     TODO: refactor
     """
     if self.mode == "festival":
         festival.sayText(s)
         return
     tts = gTTS(text=s, lang='en')
     tts.save("speech.mp3")
     if self.mode == "pyglet":
         song = pyglet.media.load('speech.mp3')
         song.play()
         # TODO fix for multiple files
     elif self.mode == "pygame":
         clock = pygame.time.Clock()
         pygame.mixer.music.load("speech.mp3")
         pygame.mixer.music.play()
         while pygame.mixer.music.get_busy():
             clock.tick(1000)
             continue
     else:
         raise Exception("Mode not found!")
         os.remove("speech.mp3")
     os.remove("speech.mp3")
     return True
예제 #23
0
    def run(self):

        
        filename = '../utils/Phrase1.mp3'
                
        tts = gTTS(self._text, lang='fr')
        tts.save(filename)
              
        #call (['play', path])
        #call (['play', '../utils/Phrase1.mp3'])
        #os.startfile('../utils/Phrase1.mp3')
        # OR
        #call(os.path.abspath('../utils/Phrase1.mp3'), shell=True)

        #clip = mp3play.load(os.path.abspath('../utils/Phrase1.mp3'))
        #clip.play()
        #
        #while clip.isplaying() is not False:
        #   time.sleep(0.5)
        
        #mp3 = pyglet.media.load(filename)
        #mp3.play()
        
        pygame.mixer.init()
        pygame.mixer.music.load(filename)
        pygame.mixer.music.set_volume(0.3)
        pygame.mixer.music.play()
        
        while pygame.mixer.music.get_busy():
            pass
예제 #24
0
def sample(args):
    with open(os.path.join(args.save_dir, 'config.pkl'), 'rb') as f:
        saved_args = cPickle.load(f)
    with open(os.path.join(args.save_dir, 'chars_vocab.pkl'), 'rb') as f:
        chars, vocab = cPickle.load(f)
    model = Model(saved_args, True)
    with tf.Session() as sess:
        tf.initialize_all_variables().run()
        saver = tf.train.Saver(tf.all_variables())
        ckpt = tf.train.get_checkpoint_state(args.save_dir)
        if ckpt and ckpt.model_checkpoint_path:
            saver.restore(sess, ckpt.model_checkpoint_path)
            ts = model.sample(sess, chars, vocab, args.n, args.prime, args.sample)
            print("Sampled Output\n")
            print(ts)
            print("Converting Text to Speech")
            tts = gTTS(text=ts, lang='en-uk')
            tts.save("ts.mp3")
            audio = MP3("ts.mp3")
            audio_length = audio.info.length
            print("Speaker is Getting Ready")
            mixer.init()
            mixer.music.load('ts.mp3')
            mixer.music.play()
            time.sleep(audio_length+5)
예제 #25
0
파일: audio.py 프로젝트: pando85/espeak-bot
def get_text_to_speech_file(text):
    tmp_file_path = '/tmp/{path}.mp3'.format( path = generate_random_string(20))
    tts = gTTS(text=text, lang='es')

    tts.save(tmp_file_path)

    return tmp_file_path
예제 #26
0
    def run(self):

        filename = '../utils/temp.mp3'

        tts = gTTS(self._text, lang='fr')
        tts.save(filename)
        call (['play', '../utils/temp.mp3'])
예제 #27
0
    def play_spoken_notifications(self, notifications=None):
        notification_mp3s = []
        for notification in notifications:
            tts = gTTS(text=notification, lang=self.tts_lang)
            now = datetime.datetime.now()
            filename = now.strftime('%Y-%m-%d_%H-%M-%S-%f') + ".mp3"
            notification_mp3s.append(filename)
            tts.save(self.webserver_path + filename)

        if notification_mp3s:
            group_coordinator = None
            for zone in list(soco.discover()):
                if zone.group.coordinator.player_name == zone.player_name:
                    group_coordinator = zone

                zone_snapshot = Snapshot(zone)
                zone_snapshot.snapshot()
                time.sleep(1)
                zone.volume = int(self.volume)
                for mp3 in notification_mp3s:
                    self.log.info('Playing notification ' + mp3 + ' on ' + zone.player_name)
                    zone.play_uri(uri='http://' + Nic().get_current_address() + ':' + self.webserver_port + '/' + mp3)
                    time.sleep(self.max_notification_seconds)
                zone_snapshot.restore()

            if group_coordinator is not None:
                for zone in list(soco.discover()):
                    if zone.group.coordinator.player_name != zone.player_name:
                        print zone.player_name + ' joining ' + zone.group.coordinator.player_name
                        zone.join(group_coordinator)
        return notifications
예제 #28
0
async def speak(server:str, channel:str, *message:str):
    chan = discord.utils.get(nepbot.get_all_channels(), server__name=server, name=channel, type=discord.ChannelType.voice)
    if not chan:
        await nepbot.say("I can't find that voice channel!")
        return

    sentence = " ".join(message)
    print(sentence)
    tts = gTTS(text=sentence, lang='ja')
    #f = TemporaryFile()
    #tts.write_to_fp(f)
    tts.save("nepsay.mp3")

    try:
        voice = await nepbot.join_voice_channel(chan)
        player = voice.create_ffmpeg_player("nepsay.mp3")
        #player = voice.create_ffmpeg_player(f, options="-v verbose", pipe=True) # TODO: get this to work

        player.start()
        while not player.is_done():
            await asyncio.sleep(1)
    except Exception as e:
        print(e)
        await nepbot.say("I failed...")
    finally:
        #f.close()
        try:
            os.remove("nepsay.mp3")
        except:
            pass
        await voice.disconnect()
예제 #29
0
파일: main.py 프로젝트: brousch/saythis2
 def sayit_google(self, text):
     print("Attempting to speak using Google TTS:\n"+text)
     tts = gTTS(text=self.saywhat_text.text, lang='en')
     tts.save("out.mp3")
     sound = SoundLoader.load("out.mp3")
     if sound:
         sound.play()
예제 #30
0
def say(message, title='Speak', speech_system='google', say=True, lang='en'):
    if speech_system == 'google':
        # Create the MP3 file which will speak the text
        folder = ''
        if '\\' in title:
            folder = '\\'.join(title.split('\\')[:-1])
        title += '.mp3'
        tts = gTTS(message, lang=lang)
        path = home+'\\'+title
        folder_path = home + "\\" + folder
        if not os.path.exists(folder_path):
            os.makedirs(folder_path)
        tts.save(path)
        if say:
            call("start /MIN {}".format(home+'\\'+title), shell=True)
    else:
        # Create the Visual Basic code which will speak the text
        with open(title + '.vbs', 'w') as file:
            file.write(
                    """
                    speaks="{}"
                    Dim speaks, speech
                    Set speech=CreateObject("sapi.spvoice")
                    speech.Speak speaks
                    """
                    .format(
                        str(message).replace('"', '').replace('\n', '')))
        # Execute the file
        call(['cscript.exe', title + '.vbs'])
예제 #31
0
	def __init__(self):
		self.tts = gTTS(text = " ", lang = 'en-us')
		self.tts.save('mp3_folder/play_file.mp3')
예제 #32
0
from gtts import gTTS
import os

tts = gTTS(text='Good morning', lang='en')
tts.save("good.mp3")
os.system("mpg321 good.mp3")
예제 #33
0
파일: tts.py 프로젝트: nshan-b/jp-getAudio
def getTTS(output_folder):
    text = input('Text: ')
    tts = gTTS(text, lang='ja')
    tts.save(output_folder + "\\" + text + ".mp3")
예제 #34
0
def on_chat_message(msg):
    content_type, chat_type, chat_id = telepot.glance(msg)
    print('Chat:', content_type, chat_type, chat_id)
    command = msg['text'].lower()
    if command == '/start':
        markup2 = ForceReply()
        # keyboard = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text=''),next key]],resize_keyboard=True)
        markup = InlineKeyboardMarkup(inline_keyboard=[[
            dict(
                text='How does it work',
                url=
                'https://telegra.ph/Lists-of-Languages-available-in-the-bot-08-12'
            )
        ]])
        responce = bot.getChat(chat_id)
        first_name = responce['first_name']
        bot.sendChatAction(chat_id, 'typing')
        bot.sendMessage(chat_id,
                        f'Hello <b>{first_name} </b>',
                        parse_mode='html',
                        reply_markup=markup2)
        bot.sendChatAction(chat_id, 'typing')
        bot.sendMessage(
            chat_id,
            'Welcome to <b>babylon<b> translator chat bot this bot will help you to translate different languges and helps you to explore more and to communicate better.',
            parse_mode='html',
            reply_markup=markup)
    elif msg['text'] != '/start':
        message = msg['text'].lower()
        value = message.split(' ')
        if not '|' in value:
            markup = ReplyKeyboardRemove()
            translator = Translator()
            translation = translator.translate(f'{message}')
            translation_src_name = LANGUAGES[translation.src]
            bot.sendChatAction(chat_id, 'typing')
            bot.sendMessage(
                chat_id,
                f'Language has been detected <b>{translation_src_name}</b>',
                parse_mode='html',
                reply_markup=markup)
            bot.sendChatAction(chat_id, 'typing')
            time.sleep(0.5)
            bot.sendMessage(chat_id, f'{translation.text}', parse_mode='html')
            bot.sendChatAction(chat_id, 'UPLOAD_AUDIO')
            tts = gTTS(message, lang='en')
            tts.save('mk.mp3')
            with open('mk.mp3', 'rb') as speech:
                bot.sendChatAction(chat_id, 'UPLOAD_AUDIO')
                bot.sendVoice(chat_id, voice=speech, caption=None)
                speech.close()
        else:
            try:
                markup = ReplyKeyboardRemove()
                message = msg['text'].lower()
                value = message.split('|')
                user_text = value[0]
                user_dest = value[-1].strip()
                translator = Translator()
                translations = translator.translate(f'{user_text}',
                                                    dest=f'{user_dest}')
                user_dest_name = LANGUAGES[user_dest]
                user_src_name = LANGUAGES[translations.src]
                bot.sendChatAction(chat_id, 'typing')
                bot.sendMessage(
                    chat_id,
                    f'From <b>{user_src_name}</b> to <b>{user_dest_name}</b>',
                    parse_mode='html')
                bot.sendMessage(chat_id,
                                f'<b>{translations.text}</b>',
                                parse_mode='html')
            except ValueError:
                bot.sendMessage(
                    chat_id,
                    f'invalid destination! what does {user_dest} means see How does it works section!'
                )
예제 #35
0
url = "http://www.vulture.com/2018/04/thanos-and-avengers-infinity-war-the-5-best-comics-to-read.html"

response = requests.get(url)

soup = BeautifulSoup(response.text, 'html.parser')

content = soup.findAll("p")
text_list = []

for element in content:
    x = element.text
    text_list.append(x)

final_text = ''.join(map(str, text_list))

tts = gTTS(text='final_text', lang='en')
tts.save('test.mp3')


def get_soup(url, header):
    request = Request(url, headers=header)
    return BeautifulSoup(urlopen(request), 'html.parser')


def main(args):
    parser = argparse.ArgumentParser(description='Scrape Google images')
    parser.add_argument('-s',
                        '--search',
                        default='bananas',
                        type=str,
                        help='search term')
import requests
import gtts

S = requests.Session()

URL = "https://en.wikipedia.org/w/api.php"

PARAMS = {
    "action": "query",
    "format": "json",
    "list": "allpages",
    "apfrom": "Nelson Mandela",
}

R = S.get(url=URL, params=PARAMS)
DATA = R.json()

PAGES = DATA["query"]["allpages"]
s1 = []

for page in PAGES:
    s1 += list(page["title"])
    res = "".join(s1)

t1 = gtts.gTTS(res)
t1.save("demo.mp3")
예제 #37
0
 def makeTTS(self, number):
     if self.text is not None:
         self.speech = gTTS(text=self.text, lang='en')
         self.speech.save(self.path[1] + "comment" + number + ".mp3")
예제 #38
0
                    action='store')
parser.add_argument('-l',
                    '--lang',
                    default='en',
                    help="ISO 639-1/IETF language tag to speak in:\n" +
                    languages())
parser.add_argument('--debug', default=False, action="store_true")

args = parser.parse_args()

try:
    if args.text:
        text = args.text
    else:
        with open(args.file, "r") as f:
            text = f.read()

    # TTSTF (Text to Speech to File)
    tts = gTTS(text=text, lang=args.lang, debug=args.debug)

    if args.destination:
        tts.save(args.destination)
    else:
        tts.write_to_fp(sys.stdout)

except Exception as e:
    if args.destination:
        print(str(e))
    else:
        print("ERROR: ", e, file=sys.stderr)
    def fn(self):

        img_counter = 0
        url = "http://192.168.43.85:8080/shot.jpg?rnd=147162"

        while True:
            imgResp = urllib.request.urlopen(url)
            imgNp = np.array(bytearray(imgResp.read()), dtype=np.uint8)
            img = cv2.imdecode(imgNp, -1)
            cv2.imshow("test", img)
            k = cv2.waitKey(1)
            if k % 256 == 32:
                img_name = "image_{}.png".format(img_counter)
                cv2.imwrite(img_name, img)
                cam_input = img_name
                ##print(img_name)
                ## print ("{} written!".format(img_name))
                img_counter += 1
                break
        cv2.destroyAllWindows()

        con = sqlite3.connect('currencies.db')

        cur = con.cursor()
        s = 'SELECT image FROM currency'
        cur.execute(s)

        r = cur.fetchall()
        max = 0
        for rw in r:
            db_image = rw[0]
            ##print(db_image)

            img1 = cv2.imread(db_image)
            img2 = cv2.imread(cam_input)

            orb = cv2.ORB_create()

            kp1, des1 = orb.detectAndCompute(img1, None)
            kp2, des2 = orb.detectAndCompute(img2, None)

            bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

            matches = bf.match(des1, des2)
            matches = sorted(matches, key=lambda x: x.distance)
            c = 0
            for m in matches:
                ##print(m.distance)
                if (m.distance) < 50.0:
                    c = c + 1

            if c > max:
                max = c
                cur.execute(
                    "SELECT cur_name,country,type,no FROM currency WHERE image=?",
                    (db_image, ))
                y = cur.fetchall()
        ##print(max)
        for i in y:
            curr = (i[0])
            country = (i[1])
            cur_index = (i[2])
            bbc = (i[3])
        speech = gTTS(country + curr)
        speech.save("hello.mp3")
        playsound('C:/Users/nagar/Desktop/b10/hello.mp3')
        self.cur_out.setText(curr)
        self.coun_out.setText(country)
        co = CurrencyRates()
        ##print(cur_index)
        ##print(bbc)
        abc = co.convert(cur_index, 'INR', bbc)
        self.inr.setText(str(abc))
예제 #40
0
async def _(event):
    if event.fwd_from:
        return
    input_str = event.pattern_match.group(1)
    start = datetime.now()
    if event.reply_to_msg_id:
        previous_message = await event.get_reply_message()
        text = previous_message.message
        lan = input_str
    elif "|" in input_str:
        lan, text = input_str.split("|")
    else:
        await event.edit("Invalid Syntax. Module stopping.")
        return
    text = text.strip()
    lan = lan.strip()
    if not os.path.isdir(Config.TMP_DOWNLOAD_DIRECTORY):
        os.makedirs(Config.TMP_DOWNLOAD_DIRECTORY)
    required_file_name = Config.TMP_DOWNLOAD_DIRECTORY + "voice.ogg"
    try:
        # https://github.com/SpEcHiDe/UniBorg/commit/17f8682d5d2df7f3921f50271b5b6722c80f4106
        tts = gTTS(text, lang=lan)
        tts.save(required_file_name)
        command_to_execute = [
            "ffmpeg",
            "-i",
            required_file_name,
            "-map",
            "0:a",
            "-codec:a",
            "libopus",
            "-b:a",
            "100k",
            "-vbr",
            "on",
            required_file_name + ".opus",
        ]
        try:
            t_response = subprocess.check_output(
                command_to_execute, stderr=subprocess.STDOUT
            )
        except (subprocess.CalledProcessError, NameError, FileNotFoundError) as exc:
            await event.edit(str(exc))
            # continue sending required_file_name
        else:
            os.remove(required_file_name)
            required_file_name = required_file_name + ".opus"
        end = datetime.now()
        ms = (end - start).seconds
        await borg.send_file(
            event.chat_id,
            required_file_name,
            # caption="Processed {} ({}) in {} seconds!".format(text[0:97], lan, ms),
            reply_to=event.message.reply_to_msg_id,
            allow_cache=False,
            voice_note=True,
        )
        os.remove(required_file_name)
        await event.edit("Processed {} ({}) in {} seconds!".format(text[0:97], lan, ms))
        await asyncio.sleep(5)
        await event.delete()
    except Exception as e:
        await event.edit(str(e))
def main():

    fail_safe = FailSafe()
    coref_solver = CorefSolver()
    print("Press H for help.")

    verbose = False
    if "--verbose" in sys.argv:
        verbose = True
        u = UtteranceBranching(coref_solver, verbose=True)
    else:
        u = UtteranceBranching(coref_solver)

    kb_file_name = None
    if "--kb" in sys.argv:
        pos = sys.argv.index("--kb")
        kb_file_name = sys.argv[pos + 1]

    q_file_name = None
    if "--q" in sys.argv:
        pos = sys.argv.index("--q")
        q_file_name = sys.argv[pos + 1]

    if kb_file_name:
        with open(kb_file_name, "r") as f:
            utterances = list(f)
            for utterance in utterances:
                print(
                    "-------------------------------------------------------")
                print(utterance)
                response = u.process(utterance[:-1])
                print(response)

    if q_file_name:
        with open(q_file_name, "r") as f:
            questions = list(f)
            for q in questions:
                print(
                    "-------------------------------------------------------")
                print(q)
                response = u.process(q[:-1])
                if response:
                    if response[-1] == "+":
                        question, fail_response, similarity = fail_safe.answer_questions(
                            q[:-1])
                        coref_solver.prev.pop()
                        # print("*********", similarity)
                        if similarity > 0.7:
                            response = fail_response
                        else:
                            response = response[:-1]
                else:
                    question, response, similarity = fail_safe.answer_questions(
                        q[:-1])
                    # print(similarity)
                    coref_solver.prev.pop()

                print("Bot: ", response)
            return

    speech_to_text = SpeechToText()

    while True:

        # type or say
        print("You: ", end='', flush=True)
        utterance = str(sys.stdin.readline())

        if utterance[:-1].lower() == "h":
            print("Press H for help.")
            print("Press S to view assistant's internal state.")
            print(
                "Press V in order to interect with the assistant with your voice."
            )
            continue

        if utterance[:-1].lower() == "s":
            u.internal_state()
            continue

        if utterance[:-1].lower() == "v":
            utterance = speech_to_text.process()
            print(utterance)
        else:
            utterance = utterance[:-1]

        response = u.process(utterance)

        if response:

            if response[-1] == "+":
                question, fail_response, similarity = fail_safe.answer_questions(
                    utterance)
                coref_solver.prev.pop()
                if similarity > 0.7:
                    response = fail_response
                else:
                    response = response[:-1]

            tts = gTTS(text=response, lang='en')
            tts.save("response.mp3")
            os.system("mpg123 response.mp3 2> /dev/null")

            print("Bot: ", response)

            if response in ["Glad we talked!", "Happy to help!", "Gooodbye!"]:
                break

        else:
            question, response, similarity = fail_safe.answer_questions(
                utterance)
            # print(similarity)
            coref_solver.prev.pop()
            print("Bot: ", response)

            tts = gTTS(text=response, lang='en')
            tts.save("response.mp3")
            os.system("mpg123 response.mp3 2> /dev/null")

        print()
예제 #42
0
def main():
    # Creating a new bot instance.
    bot = Bot(token=TOKEN, name=NAME, version=VERSION, api_url_base=API_URL)

    # Registering handlers #
    # -------------------- #
    # Handler for start command
    bot.dispatcher.add_handler(StartCommandHandler(callback=start_cb))

    # Handler for help command
    bot.dispatcher.add_handler(HelpCommandHandler(callback=help_cb))

    # Any other user command handler
    bot.dispatcher.add_handler(CommandHandler(command="test", callback=test_cb))

    # Handler for feedback command
    bot.dispatcher.add_handler(FeedbackCommandHandler(target=OWNER))

    # Handler for unknown commands
    bot.dispatcher.add_handler(UnknownCommandHandler(callback=unknown_command_cb))

    # Handler for private command with filter by user
    bot.dispatcher.add_handler(CommandHandler(
        command="restart",
        filters=Filter.sender(user_id=OWNER),
        callback=private_command_cb
    ))

    # Handler for add user to chat
    bot.dispatcher.add_handler(NewChatMembersHandler(callback=new_chat_members_cb))

    # Handler for left user from chat
    bot.dispatcher.add_handler(LeftChatMembersHandler(callback=left_chat_members_cb))

    # Handler for pinned message
    bot.dispatcher.add_handler(PinnedMessageHandler(callback=pinned_message_cb))

    # Handler for unpinned message
    bot.dispatcher.add_handler(UnPinnedMessageHandler(callback=unpinned_message_cb))

    # Handler for edited message
    bot.dispatcher.add_handler(EditedMessageHandler(callback=edited_message_cb))

    # Handler for deleted message
    bot.dispatcher.add_handler(DeletedMessageHandler(callback=deleted_message_cb))

    # Handler for message with bot mention
    bot.dispatcher.add_handler(MessageHandler(
        filters=Filter.message & Filter.mention(user_id=bot.uin),
        callback=message_with_bot_mention_cb
    ))

    # Handler for mention something else
    bot.dispatcher.add_handler(MessageHandler(
        filters=Filter.mention() & ~Filter.mention(user_id=bot.uin),
        callback=mention_cb
    ))

    # Handler for simple text message without media content
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.text, callback=message_cb))

    # Handler with regexp filter
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.regexp("^\d*$"), callback=regexp_only_dig_cb))

    # Handler for no media file. For example, text file
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.data, callback=file_cb))

    # Handlers for other file types
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.image, callback=image_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.video, callback=video_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.audio, callback=audio_cb))

    # Handler for sticker
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.sticker, callback=sticker_cb))

    # Handler for url
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.url & ~Filter.sticker, callback=url_cb))

    # Handlers for forward and reply getting
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.forward, callback=forward_cb))
    bot.dispatcher.add_handler(MessageHandler(filters=Filter.reply, callback=reply_cb))

    # Send command like this:
    # /pin 6752793278973351456
    # 6752793278973351456 - msgId
    # Handler for pin command
    bot.dispatcher.add_handler(CommandHandler(command="pin", callback=pin_cb))

    # Send command like this:
    # /unpin 6752793278973351456
    # 6752793278973351456 - msgId
    # Handler for unpin command
    bot.dispatcher.add_handler(CommandHandler(command="unpin", callback=unpin_cb))

    # Starting a polling thread watching for new events from server. This is a non-blocking call
    # ---------------------------------------------------------------------------------------- #
    bot.start_polling()

    # Call bot methods
    # -------------- #
    # Get info about bot
    bot.self_get()

    # Send message
    response = bot.send_text(chat_id=OWNER, text="Hello")
    msg_id = response.json()['msgId']

    # Reply
    bot.send_text(chat_id=OWNER, text="Reply to 'Hello'", reply_msg_id=msg_id)

    # Forward
    bot.send_text(chat_id=OWNER, text="Forward 'Hello'", forward_msg_id=msg_id, forward_chat_id=OWNER)

    # Send binary file
    with io.StringIO() as file:
        file.write('x'*100)
        file.name = "file.txt"
        file.seek(0)
        response = bot.send_file(chat_id=OWNER, file=file.read(), caption="binary file caption")
        file_id = response.json()['fileId']

    # Get file info
    bot.get_file_info(file_id=file_id)

    # Send file by file_id
    bot.send_file(chat_id=OWNER, file_id=file_id, caption="file_id file caption")

    # Send file by file_id as reply to message
    bot.send_file(chat_id=OWNER, file_id=file_id, caption="file_id file caption", reply_msg_id=msg_id)

    # Forward file by file_id
    bot.send_file(
        chat_id=OWNER,
        file_id=file_id,
        caption="file_id file caption",
        forward_msg_id=msg_id,
        forward_chat_id=OWNER
    )

    # Send voice file
    with io.BytesIO() as file:
        gTTS('Hello everybody!').write_to_fp(file)
        file.name = "hello_voice.mp3"
        file.seek(0)
        response = bot.send_voice(chat_id=OWNER, file=file.read())
        hello_voice_file_id = response.json()['fileId']

    # Send voice by file_id
    bot.send_voice(chat_id=OWNER, file_id=hello_voice_file_id)

    # Edit text
    msg_id = bot.send_text(chat_id=OWNER, text="Message to be edited").json()['msgId']
    bot.edit_text(chat_id=OWNER, msg_id=msg_id, text="edited text")

    # Delete message
    msg_id = bot.send_text(chat_id=OWNER, text="Message to be deleted").json()['msgId']
    bot.delete_messages(chat_id=OWNER, msg_id=msg_id)

    # Send typing action
    bot.send_actions(chat_id=OWNER, actions=["typing"])
    sleep(1)
    # Stop typing
    bot.send_actions(chat_id=OWNER, actions=[])

    # Get info about chat
    bot.get_chat_info(chat_id=TEST_CHAT)

    # Get chat admins
    bot.get_chat_admins(chat_id=TEST_CHAT)
    # Get chat members
    bot.get_chat_members(chat_id=TEST_CHAT)
    # Get chat blocked users
    bot.get_chat_blocked_users(chat_id=TEST_CHAT)
    # Get chat pending users
    bot.get_chat_pending_users(chat_id=TEST_CHAT)

    # Block user in chat
    bot.chat_block_user(chat_id=TEST_CHAT, user_id=TEST_USER, del_last_messages=True)
    # Unlock user in chat
    bot.chat_unblock_user(chat_id=TEST_CHAT, user_id=TEST_USER)

    # Chat resolve pending user or everyone
    bot.chat_resolve_pending(chat_id=TEST_CHAT, approve=True, user_id=TEST_USER, everyone=False)

    # Set chat title
    bot.set_chat_title(chat_id=TEST_CHAT, title="TEST TITLE")
    # Set chat about
    bot.set_chat_about(chat_id=TEST_CHAT, about="TEST ABOUT")
    # Set chat title
    bot.set_chat_rules(chat_id=TEST_CHAT, rules="TEST RULES")

    # Send bot buttons
    bot.send_text(chat_id=OWNER,
                  text="Hello with buttons.",
                  inline_keyboard_markup="[{}]".format(json.dumps([
                      {"text": "Action 1", "url": "http://mail.ru"},
                      {"text": "Action 2", "callbackData": "call_back_id_2"},
                      {"text": "Action 3", "callbackData": "call_back_id_3"}
                  ])))

    # Handler for bot buttons reply.
    bot.dispatcher.add_handler(BotButtonCommandHandler(callback=buttons_answer_cb))

    bot.idle()
예제 #43
0
# Import the Gtts module for text
# to speech conversion
from gtts import gTTS

# import Os module to start the audio file
import os
mytext = "This is a test line."
# Language we want to use
language = 'en'
myobj = gTTS(text=mytext, lang=language, slow=False)
myobj.save("mytext.mp3")
# Play the converted file
os.system("start output.mp3")
예제 #44
0
from gtts import gTTS
import json
import requests
import sys
import os

# Get yours id and key via https://oxforddictionaries.com
app_id = '********'
app_key = '********************************'

endpoint = "entries"
lang = "en-us"
word = sys.argv[1]

try:
    url = "https://od-api.oxforddictionaries.com/api/v2/" + endpoint + "/" + lang + "/" + word.lower()
    response = requests.get(url, headers={"app_id":app_id, "app_key":app_key})
    data = response.json()
    audioOut = data['results'][0]['lexicalEntries'][0]['entries'][0]['senses'][0]['definitions'][0]
    aud = gTTS(text=audioOut, lang="en", slow=False)
except:
    audioOut = "Sorry, couldn't find"
    aud = gTTS(text=audioOut, lang="en", slow=False)
    
aud.save("aud.mp3")
print(word+" : "+audioOut)

os.system("mpg123 -q aud.mp3")
os.remove("aud.mp3")
예제 #45
0
	def set_phrase(self, phrase, ln):
		self.tts = gTTS(text = phrase, lang = ln)
		self.save_to_file()
import speech_recognition as sr
from gtts import gTTS
#from pygame import mixer
#import os

while (True):
    r = sr.Recognizer()
    with sr.Microphone() as source:
        print("Listening from microphone........")
        print("Say something!")
        audio = r.listen(source, phrase_time_limit=0)
        response = r.recognize_google(audio)
        print("I think you said '" + response + "'")
        tts = gTTS(text="I think you said " + str(response), lang='en')
예제 #47
0
def text_to_speech(text):
    tts = gTTS(text=text)
    filename = "AudioBook.mp3"
    tts.save(filename)
예제 #48
0
def cria_audio(mensagem):
    tts = gTTS(mensagem, lang='pt-br')
    tts.save('audios/mensagem.mp3')
    print('ROSIE:  ', mensagem)
    call(['afplay', 'audios/mensagem.mp3'])  # OSX
#Instale com o CMD digitando pip install gtts
from gtts import gTTS  #Importa o módulo Google Text-to-Speech (Síntese de voz Google)
import os  #Apenas para executar o áudio após ele ser salvo

#Abre um arquivo de texto no modo leitura e lê o conteúdo
arquivoTexto = open('arquivo.txt')
conteudoArquivo = arquivoTexto.read()

#Escolhe o idioma, pt-br é o português brasileiro, para inglês escreva idioma = "en"
idioma = "pt-br"

#Pega a voz do tradutor do Google no idioma selecionado com o conteúdo passado,
#   é necessário estar conectado a internet para funcionar
audio = gTTS(text=conteudoArquivo, lang=idioma, slow=False)

#Salva e executa o áudio
audio.save("áudio.mp3")
os.system("áudio.mp3")

arquivoTexto.close()  #Fecha o arquivo
예제 #50
0
def on_message(data: aminofix.objects.Event):
    global ban
    global tim
    global nom

    chatId = data.message.chatId
    nickname = data.message.author.nickname
    content = data.message.content
    id = data.message.messageId
    title: str = client.get_community_info(data.comId).name
    userId: str = data.message.author.userId

    if not content: content = "None"

    lis = [
        'Думаю, что да', 'Думаю, что нет', 'Наверное', 'Уверена на все 100%',
        'Точно нет', 'Да, почему бы и нет?',
        'Скорее всего да, а хотя, может и нет...',
        'Я не знаю ответа на этот вопрос, я глупая', 'Почему ты так думаешь?',
        'Я не уверена что тебе стоит знать ответ на твой вопрос', 'Нет', 'Да'
    ]

    lis2 = [
        '*обняла в ответ* мне приятно что ты заботишься о мне~',
        'Ня~ Как приятно~', '*обняла в ответ* Не отпускай меня...',
        '*обняла в ответ* Можно нам так стоять вместе вечно?..',
        '*обняла в ответ* Я люблю тебя..', '*обняла в ответ* :3',
        '*обняла в ответ* я счастлива~'
    ]

    lis3 = [
        'Привет', "Здравствуй", "hola mi amigo", "Привет, зая", "Мур-Мур~",
        "Да-да, это я"
    ]

    lisen = [
        'I think so, yes.', "I don't think so", 'Probably',
        "I'm 100% sure of it", 'Absolutely not.', 'Yeah, why not?',
        'Most likely yes, but maybe not...',
        "I don't know the answer to that question, I'm stupid",
        'What makes you think that?',
        "I'm not sure you should know the answer to your question", 'No', 'Yes'
    ]

    lis2en = [
        "*hugged me back* I'm glad you care about me~", 'Nyah~ How nice~',
        "*Hugged me back* Don't let me go...",
        '*Hugged back* Can we stand like this together forever?',
        '*hugged back* I love you...', '*hugged back* :3',
        "*hugged back* I'm happy~"
    ]

    lis3en = [
        'Hi', 'Hello', 'hola mi amigo', 'Hi, poochie', 'Mur-Mur~',
        "Yes, yes, it's me"
    ]

    print(nickname, content, title)

    if content.lower().startswith("команды") or content.lower().startswith(
            "помощь") or content.lower().startswith("help"):
        if translator == "ru":
            sub_client.send_message(message="""
[B]Команды:

Люблю - Покажите Рам свою любовь!
Рам - Поздоровайтесь с Рам!
Действия - Взаимодействия с участниками
*обнял* или *обняла* - обнять Рам!
Вопрос, - спроси у Рам что- либо!
Гс - Попроси Рам записать голсовое сообщение!
Любовь - узнай вероятность любви между людьми
АдПанель - админская панель
Инфо - информация профиля
Создательница - О создателе Рам
Информация - список обновления Рам!
""",
                                    chatId=chatId)
        elif translator == "en":
            sub_client.send_message(message="""
[B]Commands:

Love - Show Ram your love!
Ram - Say hello to Ram!
Actions - Interactions with participants
*hugged* - hug Ram!
Question - Ask Ram anything!
Gs - Ask Ram to write down a voice message!
Lovers - Find out the possibility of love between people.
AdPanel - admin panel.
Info - Profile Info.
Creator - About Ram's Creator!
Information - Ram's update list!
""",
                                    chatId=chatId)

    if content.lower().startswith("рам") or content.lower().startswith("ram"):
        if translator == "ru":
            sub_client.send_message(message=str(random.choice(lis3)),
                                    chatId=chatId,
                                    replyTo=id)
        elif translator == "en":
            sub_client.send_message(message=str(random.choice(lis3en)),
                                    chatId=chatId,
                                    replyTo=id)

    if content.lower().startswith("онлайн") or content.lower().startswith(
            "online"):
        if data.message.author.role != 0:
            if translator == "ru":
                sub_client.activity_status('online')
                sub_client.send_message(message="Я в сети!", chatId=chatId)
            elif translator == "en":
                sub_client.activity_status('online')
                sub_client.send_message(message="I'm online", chatId=chatId)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("оффлайн") or content.lower().startswith(
            "offline"):
        if data.message.author.role != 0:
            if translator == "ru":
                sub_client.activity_status('offline')
                sub_client.send_message(message="Я вне сети!", chatId=chatId)
            elif translator == "en":
                sub_client.activity_status('offline')
                sub_client.send_message(message="I'm offline!", chatId=chatId)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("вопрос,") or content.lower().startswith(
            "question,"):
        if translator == "ru":
            sub_client.send_message(message=str(random.choice(lis)),
                                    chatId=chatId,
                                    replyTo=id)
        elif translator == "en":
            sub_client.send_message(message=str(random.choice(lisen)),
                                    chatId=chatId,
                                    replyTo=id)

    if content.lower().startswith("люблю") or content.lower().startswith(
            "love"):
        if translator == "ru":
            sub_client.send_message(message="Я тоже тебя люблю",
                                    chatId=chatId,
                                    replyTo=id)
        elif translator == "en":
            sub_client.send_message(message="I love you too",
                                    chatId=chatId,
                                    replyTo=id)

    if content.lower().startswith("lovers") or content.lower().startswith(
            "любовь"):
        mentions = data.message.extensions.get('mentionedArray')
        if mentions != None and len(mentions) == 2:
            pidorasi = [
                sub_client.get_user_info(x['uid']).nickname for x in mentions
            ]
            if translator == "ru":
                sub_client.send_message(
                    message=
                    f"Вероятность того, что {pidorasi[0]} и {pidorasi[1]} любят друг друга равно {random.randint(0, 100)}%",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    f"The probability that  {pidorasi[0]} and {pidorasi[1]} love each other: {random.randint(0, 100)}%",
                    chatId=chatId)

    if content.lower().startswith("*обнял*") or content.lower().startswith(
            "*обняла*") or content.lower().startswith("*hugged*"):
        if translator == "ru":
            sub_client.send_message(message=str(random.choice(lis2)),
                                    chatId=chatId,
                                    replyTo=id)
        elif translator == "en":
            sub_client.send_message(message=str(random.choice(lis2en)),
                                    chatId=chatId,
                                    replyTo=id)

    if content.lower().startswith("информация") or content.lower().startswith(
            "information"):
        if translator == "ru":
            sub_client.send_message(message='''
[B]Обновления: 1.1.1

==Изменения:==
-Полный перенос Рам на условно новую библиотеку, дважды))
-Сделаны мини исправления

==Удалено:==
-Старая бибилиотека бота, тоже дважды)
''',
                                    chatId=chatId)
        elif translator == "en":
            sub_client.send_message(message='''
[B]Update: 1.1.1

This is the biggest update since the creation of Ram!

==Changes:==
-Full transfer of Ram to a conditional new library, twice))


==Removed:==
-Old bot bibliography, also twice)
-Minimum corrections have been made
''',
                                    chatId=chatId)

    if content.lower().startswith(
            "создательница") or content.lower().startswith("creator"):
        if translator == "ru":
            sub_client.send_message(message='''
Версия бота 1.1.1

==Создательница:==
Дискорд - CamilaTokisaki#5351
Телеграмм - @CamilaTokisaki
github - https://github.com/CamilaTokisaki
Почта - [email protected]

==Особая благодарность:==
WildNightFox - За помощь с переносом библиотеки и доп командой
Его дискорд: WildNightFox#9154

И всё, больше я никому не благодарна :3
''',
                                    chatId=chatId)
        elif translator == "en":
            sub_client.send_message(message='''
Bot version 1.1.1

==Creator:==
Discord - CamilaTokisaki#5351
Telegram - @CamilaTokisaki
github - https://github.com/CamilaTokisaki
E-mail - [email protected]

==Special thanks:==
WildNightFox - For help with migrating the library and adding commands
His discord: WildNightFox#9154

And that's it, I'm not grateful to anyone else :3
''',
                                    chatId=chatId)

    if content.lower().startswith("действия") or content.lower().startswith(
            "actions"):
        if translator == "ru":
            sub_client.send_message(message='''
[B]Действия:

щекочет - Прижаться
кормит - Покормить
обнимает - Обнять
целует - Поцеловать
гладит - Погладить
тыкает - Тыкнуть
бьёт - ударить
щекочет - Пощекотать
кусает - делать кусь
''',
                                    chatId=chatId)

        elif translator == "en":
            sub_client.send_message(message='''
[B]Actions:

cuddle - Cuddle up
feed - feed
hug - Hug
kiss - Kiss
pat - Stroke
poke - Poke
slap - slap
tickle - Tickle
kus - give a bite
''',
                                    chatId=chatId)

    if content.lower().startswith("tickle") or content.lower().startswith(
            "щекочет"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} щекочет {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} tickles {author2}',
                chatId=chatId)

    if content.lower().startswith("slap") or content.lower().startswith(
            "бьёт"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} бьёт {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} beats {author2}',
                chatId=chatId)

    if content.lower().startswith("poke") or content.lower().startswith(
            "тыкает"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} тыкает в {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} pokes at {author2}',
                chatId=chatId)

    if content.lower().startswith("pat") or content.lower().startswith(
            "гладит"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} гладит {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=
                f'{data.message.author.nickname} gently strokes {author2}',
                chatId=chatId)

    if content.lower().startswith("hug") or content.lower().startswith(
            "обнимает"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} обнимает {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} hugs {author2}',
                chatId=chatId)

    if content.lower().startswith("feed") or content.lower().startswith(
            "кормит"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} кормит {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} feeds {author2}',
                chatId=chatId)

    if content.lower().startswith("cuddle") or content.lower().startswith(
            "прижимается"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=
                f'{data.message.author.nickname} прижимается к {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=
                f'{data.message.author.nickname} snuggles up to {author2}',
                chatId=chatId)

    if content.lower().startswith("kiss") or content.lower().startswith(
            "целует"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} целует {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} kisses {author2}',
                chatId=chatId)

    if content.lower().startswith("kus") or content.lower().startswith(
            "кусает"):
        author2 = data.message.content.split("@")[1].replace("@", "")[0:50]
        if translator == "ru":
            sub_client.send_message(
                message=f'{data.message.author.nickname} делает кусь {author2}',
                chatId=chatId)
        elif translator == "en":
            sub_client.send_message(
                message=f'{data.message.author.nickname} makes a kus {author2}',
                chatId=chatId)

    if content.lower().startswith("инфо") or content.lower().startswith(
            "info"):
        repa = sub_client.get_user_info(userId=userId).reputation
        lvl = sub_client.get_user_info(userId=userId).level
        crttime = sub_client.get_user_info(userId=userId).createdTime[0:10]
        followers = sub_client.get_user_achievements(
            userId=userId).numberOfFollowersCount
        profilchange = sub_client.get_user_info(
            userId=userId).modifiedTime[0:10]
        commentz = sub_client.get_user_info(userId=userId).commentsCount
        posts = sub_client.get_user_achievements(
            userId=userId).numberOfPostsCreated
        followed = sub_client.get_user_info(userId=userId).followingCount
        if translator == "ru":
            sub_client.send_message(chatId=data.message.chatId,
                                    message=f"""
Никнейм: {nickname}
Дата Создания Аккаунта: {crttime}
Последний раз профиль изменялся: {profilchange}
Количество Репутации: {repa}
Уровень Аккаунта: {lvl}
Количество постов созданных в профиле: {posts}
Количество комментариев на стене профиля: {commentz}
Количество людей на которых вы подписаны: {followed}
Подписчики аккаунта: {followers}
	""")
        elif translator == "en":
            sub_client.send_message(chatId=data.message.chatId,
                                    message=f"""
Nickname: {nickname}
Account Creation Date: {crttime}
The last time the profile was changed: {profilchange}
Number of Reputation: {repa}
Account Level: {lvl}
Number of posts created in the profile: {posts}
Number of comments on the profile wall: {comments}
The number of people you are subscribed to: {followed}
Account subscribers: {followers}
	""")

    if content.lower().startswith("гс") or content.lower().startswith("gs"):
        if translator == "ru":
            myobj = gTTS(text=data.message.content[4:], lang='ru', slow=False)
            myobj.save("gs.mp3")
            with open("gs.mp3", "rb") as file:
                sub_client.send_message(chatId=chatId,
                                        file=file,
                                        fileType="audio")
        elif translator == "en":
            myobj = gTTS(text=data.message.content[4:], lang='en', slow=False)
            myobj.save("gs.mp3")
            with open("gs.mp3", "rb") as file:
                sub_client.send_message(chatId=chatId,
                                        file=file,
                                        fileType="audio")

    if content.lower().startswith("адпанель") or content.lower().startswith(
            "adpanel"):
        if data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(message="""
[B]Админ Панель
Онлайн - Рам появлится в списке "В сети"
Оффлайн - Рам перестанет высввечтиваться
Зачистка - Чистит 10 сообщений (с учётом этого)
СуперЧистка - Чистит 100 сообщений
""",
                                        chatId=chatId,
                                        replyTo=id)
            elif translator == "en":
                sub_client.send_message(message="""
[B]Admin Panel.
Online - Ram will appear in the "Online" list
Offline - Ram will no longer appear
Cleanup - Cleans up 10 posts (includes this one)
SuperClean - Cleans 100 messages
""",
                                        chatId=chatId,
                                        replyTo=id)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("!ночь") or content.lower().startswith(
            "!night"):
        if data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message="*зевая* Спокойной ночи сладкие мои~",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message="*singing* Good night my sweethearts~",
                    chatId=chatId)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("!утро") or content.lower().startswith(
            "!morn"):
        if data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "*потирая сонные глазки улыбаясь* Доброе утро лапочки~",
                    chatId=cahtId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "*rubbing sleepy eyes and smiling* Good morning, darlings~",
                    chatId=cahtId)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("зачистка") or content.lower().startswith(
            "сleanup"):
        if data.message.author.role != 0:
            for msgId in sub_client.get_chat_messages(
                    chatId=data.message.chatId, size=10).messageId:
                sub_client.delete_message(reason="зачистка",
                                          chatId=data.message.chatId,
                                          messageId=msgId,
                                          asStaff=True)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if content.lower().startswith("суперчистка") or content.lower().startswith(
            "superclean"):
        if data.message.author.role != 0:
            for msgId in sub_client.get_chat_messages(
                    chatId=data.message.chatId, size=100).messageId:
                sub_client.delete_message(reason="суперчистка",
                                          chatId=data.message.chatId,
                                          messageId=msgId,
                                          asStaff=True)
        elif not data.message.author.role != 0:
            if translator == "ru":
                sub_client.send_message(
                    message=
                    "Прости, но у меня или у тебя нет прав на выполнения этой команды",
                    chatId=chatId)
            elif translator == "en":
                sub_client.send_message(
                    message=
                    "I'm sorry, but I or you do not have the authority to execute this command",
                    chatId=chatId)

    if [
            x for x in
        [
            '.tickle', '.kus', '.slap', '.poke', '.hug', '.cuddle', '.feed',
            '.kiss', '.pat', '!утро', '!ночь', 'гс', '!morn', '!night', 'gs'
        ] if (x in content)
    ]:
        sub_client.delete_message(reason="зачистка чата",
                                  chatId=data.message.chatId,
                                  messageId=data.message.messageId,
                                  asStaff=True)
예제 #51
0
파일: ego.py 프로젝트: Oreyin/EGO
def speak(audioString):
    print(audioString)
    tts = gTTS(text=audioString, lang='en')
    tts.save("audio.mp3")
    os.system("mpg321 audio.mp3")
import os
from pypollen import Pollen
import time
from geopy.geocoders import Nominatim
from gtts import gTTS
geolocator = Nominatim()
#Images
cwd = os.getcwd()
while True:
    location = geolocator.geocode("Blackpool")
    lat = location.latitude
    lon = location.longitude
    pollen_status = Pollen(lat, lon).pollencount
    text = "The pollen level at your location is " + pollen_status
    speech = (gTTS(text=text))
    speech.save(cwd + "/speech.mp3")
    speech_path = "cmdmp3.exe " + cwd + "/speech.mp3"
    os.system(speech_path)
    time.sleep(15)
# AUDIO_FILE = path.join(path.dirname(path.realpath(__file__)), "chinese.flac")

translator = Translator()
# use the audio file as the audio source
r = sr.Recognizer()

for index in range(1, 51):
    mp3 = AudioSegment.from_mp3(str(index).zfill(4) + "FR_A.mp3")
    mp3.export(str(index).zfill(4) + "FR_A.wav", format="wav")

    with sr.AudioFile(str(index).zfill(4) + "FR_A.wav") as source:

        audio = r.record(source)  # read the entire audio file
        # try:
        # for testing purposes, we're just using the default API key
        # to use another API key, use `r.recognize_google(audio, key="GOOGLE_SPEECH_RECOGNITION_API_KEY")`
        # instead of `r.recognize_google(audio)`
        recognisedText = r.recognize_google(audio, language="fr")
        print("Google Speech Recognition thinks you said " + recognisedText)
        #except sr.UnknownValueError:
        #    print("Google Speech Recognition could not understand audio")
        #except sr.RequestError as e:
        #     print("Could not request results from Google Speech Recognition service; {0}".format(e))

        tts = gTTS(text=recognisedText, lang='fr')
        tts.save(str(index).zfill(4) + "FR_B.mp3")

        tts = gTTS(text=translator.translate(recognisedText, dest='en').text,
                   lang='en')
        tts.save(str(index).zfill(4) + "EN_A.mp3")
def analysis(span):
    pygame.init()
    
    
    
    price=float(span.text)
    final_lst.append(price)
    
    length=len(final_lst)
    
    
    if length!=1:
        
    
        if final_lst[length-1]>final_lst[length-2]: #New Price is higher than the Previous Price
            
            pygame.mixer.music.load('Ta_da.mp3')
            pygame.mixer.music.play(0)
            
            change_percentage=float((final_lst[length-1]-final_lst[length-2])/final_lst[length-2])*100
            
            text="B M S Stock Price went up by "+str(change_percentage)+" percent"
            print(text)
            myobj = gTTS(text=text, lang='en', slow=False) 
            myobj.save("text.mp3") 
            pygame.mixer.music.load('text.mp3')
            pygame.mixer.music.play(0)

        
        elif final_lst[length-1]<final_lst[length-2]: # New price is lower than previous price
     
            pygame.mixer.music.load('Sad.mp3')
            pygame.mixer.music.play(0)
            
            change_percentage=float(abs(final_lst[length-1]-final_lst[length-2])/final_lst[length-2])*100
            text="B M S Stock Price went down by "+str(change_percentage)+" percent"
            print(text)
            myobj = gTTS(text=text, lang='en', slow=False) 
            myobj.save("text.mp3") 
            pygame.mixer.music.load('text.mp3')
            pygame.mixer.music.play(0)

            
        
        else:
            
            print("No Change")
            change_percentage=float(abs(final_lst[length-1]-final_lst[length-2])/final_lst[length-2])*100
            text="B M S stock price has not changed."
            
            myobj = gTTS(text=text, lang='en', slow=False) 
            myobj.save("text.mp3") 
            pygame.mixer.music.load('text.mp3')
            pygame.mixer.music.play(0)
            os.remove("text.mp3") #remove the file from the system
            

            
    
    
    
    df.loc[len(df)] = [price]
    plotgraph(df)
예제 #55
0
import pyttsx3
import PyPDF2
from gtts import gTTS

pdfReader = PyPDF2.PdfFileReader(open('jk.pdf', 'rb'))
engine = pyttsx3.init()

engine.setProperty('rate', 150)
voices = engine.getProperty('voices')
print(voices)
engine.setProperty('voice', voices[0].id)
volume = engine.getProperty('volume')
print(volume)
engine.setProperty('volume', 2)

for page in range(pdfReader.numPages):
    t = pdfReader.getPage(page).extractText()
    engine.say(t)
    engine.runAndWait()

tts = gTTS(text=t, lang='en')
tts.save("jk.mp3")
print("sucesss")
engine.runAndWait()
engine.stop()
from gtts import gTTS

sentences = [
    'Bem-vindo ao Blind Guide, aguarde enquanto estabelecemos conexão GPS.',
    'Tudo pronto. Vamos. Siga em frente.', 'Em dois metros, vire à esquerda.',
    'Em um metro, vire à esquerda.', 'Prepare-se para virar à esquerda.',
    'Vire à esquerda!', 'Em dois metros, vire à direita.',
    'Em um metro, vire à direita.', 'Prepare-se para virar à direita.',
    'Vire à direita!', 'Você chegou ao seu destino.',
    'Você chegou, destino está à sua esquerda.',
    'Você chegou, obrigado por contar com nosso guia!',
    'Chegamos ao fim do nosso vídeo, obrigado pela atenção!',
    'Como posso ajudar?', 'Olhe para direita!', 'Olhe para esquerda!',
    'Aguardando passagem de veículos.', 'Tudo limpo, atravesse com cuidado!'
]

file_names = [
    'welcome.mp3', 'ready.mp3', '2m_left.mp3', '1m_left.mp3', 'prep_left.mp3',
    'left.mp3', '2m_right.mp3', '1m_right.mp3', 'prep_right.mp3', 'right.mp3',
    'reached.mp3', 'reached_left.mp3', 'reached_thanks.mp3',
    'ending_presentation.mp3', 'help.mp3', 'look_right.mp3', 'look_left.mp3',
    'waiting.mp3', 'all_clear.mp3'
]
print(f'{len(sentences)} e {len(file_names)}')
for sentence, name in zip(sentences, file_names):
    sound = gTTS(text=sentence, lang='pt-BR')
    sound.save(name)
    print(f'File {name} saved!')
                                lst=human_string.split()
                                human_string=" ".join(lst[0:2])
                                human_string_filename=str(lst[0])

                        current= time.time()
                        fps=frame_count/(current-start)

                # Speech module        
                if last>40 and pygame.mixer.music.get_busy() == False and  human_string==human_string_n:
                        pred+=1
                        name=human_string_filename+".mp3"

                        # Only get from google if we dont have it
                        if not os.path.isfile(name):
                                tts = gTTS(text="I see a "+human_string, lang='en')
                                tts.save(name)

                        last=0
                        pygame.mixer.music.load(name)
                        pygame.mixer.music.play()

                # Show info during some time              
                if last<40 and frame_count>10:
                        cv2.putText(frame,human_string, (20,400), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,255,255))
                        cv2.putText(frame,str(np.round(score,2))+"%", (20,440), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,255,255))

                if frame_count>20:
                        cv2.putText(frame,"fps: "+str(np.round(fps,2)), (460,460), cv2.FONT_HERSHEY_TRIPLEX, 1, (255,255,255))

                cv2.imshow("Frame", frame)
예제 #58
0
def speak(text):
    tts = gTTS(text=text, lang="en")
    tts.save("tmp.mp3")
    qn_audio = AudioSegment.from_mp3("tmp.mp3")
    play(qn_audio)
    os.remove("tmp.mp3")
예제 #59
0
 def to_tts(self, text):
     tts = gTTS(text=text, lang=LANG)
     tts.save("{name}.{type}".format(name=self.filename,
                                     type=self.filetype))
예제 #60
0
if team2=="WI":
    team2 = "west indies"
if team2=="AUS":
    team2 = "australia"
if team2=="PAK":
    team2 = "pakistan"
if team2=="AFG":
    team2 = "afghanistan"
if team2=="IND":
    team2 = "india"



team = team.replace(" v "," vs ")
score1=score1.replace("/"," for ")
score1=score1.replace("."," point ")
score1=score1.replace("("," in ")

score2=score2.replace("/"," for ")
score2=score2.replace("."," point ")
score2=score2.replace("("," in ")
score2=score2.replace("Ovs" ,"overs ")
team2=team2.replace("RSA","southafrica")
team2=team2.replace(">","")

output = team + "    "+  team1  + "    "+ "scored" + "    "+ score1  + "overs" + "       "+ team2 + "    " + "scored" + "     "+ score2

tts = gTTS(text=output, lang='en-us')
tts.save("hell.mp3")
os.system("mpg321 hel.mp3")