Example #1
0
def translate(mora_src):
    result = []

    # アプリケーション名とキーの設定
    client_secret = '0cad3399b0214a31acafe914d6cac203'
    auth_client = AzureAuthClient(client_secret)
    bearer_token = 'Bearer ' + auth_client.get_access_token()

    headers = {"Authorization ": bearer_token}

    for ms in mora_src:
        # Call to Microsoft Translator Service
        translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text={}&to={}".format(
            ms[1], "ja")
        translationData = requests.get(translateUrl, headers=headers)
        # parse xml return values
        translation = ElementTree.fromstring(
            translationData.text.encode('utf-8'))
        obj_ln = translation.text

        obj_ln = obj_ln.encode('utf-8')
        obj_ln = obj_ln.replace("。", "")
        obj_ln = obj_ln.replace("・", "")
        # 英語が残ってしまった場合は削除
        obj_ln = re.sub(r'[a-zA-Z]+', "", obj_ln)
        print(obj_ln)
        result.append((ms[0], ms[1], obj_ln))

    return result
Example #2
0
 def translate(self, query, to):
     auth_client = AzureAuthClient(key.Translator.key)
     auth_token = auth_client.get_access_token()
     bearer_token = 'Bearer '.encode('utf-8') + auth_token
     headers = {"Authorization ": bearer_token}
     url = ("http://api.microsofttranslator.com/v2/Http.svc/Translate?" +
            "text={}&to={}".format(query, to))
     data = requests.get(url, headers=headers)
     return ElementTree.fromstring(data.text.encode('utf-8')).text
Example #3
0
 def translate(self, query, to):
     auth_client = AzureAuthClient(key.Translator.key)
     auth_token = auth_client.get_access_token()
     bearer_token = 'Bearer '.encode('utf-8') + auth_token
     headers = {"Authorization ": bearer_token}
     url = ("http://api.microsofttranslator.com/v2/Http.svc/Translate?" +
            "text={}&to={}".format(query, to))
     data = requests.get(url, headers=headers)
     return ElementTree.fromstring(data.text.encode('utf-8')).text
Example #4
0
def synthesize(dir, cap_path):
    client_secret = 'e9fc657f5c9247cfac2a9ff582a91716'
    auth_client = AzureAuthClient(client_secret)

    # name = "squirrel"

    s = ""
    data = []
    with open(dir + cap_path) as f:
        j = json.loads(f.read())
    for c in j:
        data.append((c["start"], c["duration"], c["text"]))
        s += c["text"]
    with open(dir + "text.txt", 'w') as f:
        f.write(s)

    for i in range(len(data)):
        time, dur, text = data[i]
        bearer_token = 'Bearer ' + auth_client.get_access_token().decode(
            'ascii')
        mp3data = TextToSpeech(bearer_token, text)
        with open("media/tmp/{}.mp3".format(i), 'wb') as f:
            f.write(mp3data)
    def next(self):
        if not self.eof_reached:
            data = self.input.readframes(self.chunk_size)
            if len(data) > 0:
                return data
            self.eof_reached = True
        if self.silence_duration > 0:
            self.silence_duration -= self.chunk_length
            return self.silence_chunk
        raise StopIteration


if __name__ == "__main__":

    client_secret = 'INSERT YOUR CLIENT SECRET'
    auth_client = AzureAuthClient(client_secret)

    # Audio file(s) to transcribe
    audio_file = 'INSERT AUDIO FILE FULL PATH'
    audio_source = WaveFileAudioSource(audio_file, 100, 2000)
    # Translate from this language. The language must match the source audio.
    # Supported languages are given by the 'speech' scope of the supported languages API.
    translate_from = 'en-US'
    # Translate to this language.
    # Supported languages are given by the 'text' scope of the supported languages API.
    translate_to = 'fr'
    # Features requested by the client.
    features = "Partial,TextToSpeech"

    # Transcription results will be saved into a new folder in the current directory
    output_folder = os.path.join(os.getcwd(), uuid.uuid4().hex)
doItAgain = "yes"


def GetTextAndTranslate(finalToken, toLang, string):
    fromLangCode = " "
    toLangCode = " "
    textToTranslate = " "

    # Get the source language
    fromLangCode = "en"
    # Get the destination language
    toLangCode = toLang
    textToTranslate = string

    # Call to Microsoft Translator Service
    headers = {"Authorization ": finalToken}
    translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text={}&to={}".format(
        textToTranslate, toLangCode)

    translationData = requests.get(translateUrl, headers=headers)
    # parse xml return values
    translation = ElementTree.fromstring(translationData.text.encode('utf-8'))
    # display translation
    return (translation.text)


client_secret = 'a7867a2553884464b0f657a74f8ef0cc'
auth_client = AzureAuthClient(client_secret)
bearer_token = 'Bearer ' + auth_client.get_access_token()
to_trans = "Ken, do you have anything to say for yourself? About this abomination, about this travesty that's in front of me right now? I didn't think so. Hey you guys, this is Austin. This disaster that sits in front of me are some of the most popular PS4 accessories. Now sure, unlike a gaming PC which you can fully customize, a PS4 is pretty much what you get is, well, what you get. However, what I'm curious about is whether any of this stuff is remotely worth it. So to start with, we have the Nyko Intercooler so they claim that this is going to direct hot air away from the console, which in theory is going to be a thing that actually could be really helpful, especially with the old, fat PS4, it could get really loud under load. So one of the things that drew me to the Intercooler is that this actually is fairly well-integrated into the PS4 design, so as you'll see in a second here, it basically just clips right on. And that's pretty much it. So what we can have here is, it looks like one large fan and a couple of smaller fans, and the cool part is, it actually has its own power pass-through so you don't need to turn this thing on or off or run any extra cables, it should just go on the back. This just clips into place, I think. That actually integrates pretty well, I've gotta say. So it's even the sort of same two-toned finish on the back, you still have access to all of your ports and you can still plug in the power cable right here. Now I'm curious how well it'll actually work but it's worth a shot. So if you're rocking the PS4 Slim or Pro then Dobe has you covered. So this is the P4 series multi-functional cooling stand. And we'll see exactly how multi-functional it really is. So the idea here is that not only can you actually get a stand, but you can also mount your controllers as well as some games all in the one stand. So here. (laughs) This is a little bit bigger. This product can decrease the temperature for the PS4 effectively, improving its performance and decreasing the power loss. The power loss? So while these cooling products claim to lower the temperature of the PS4, that really shouldn't give you more performance. The real advantage and the thing that I'm going to be looking for is if temperatures come down, in theory, fan noise should come down and potentially longevity of your PS4 should be improved a little bit, but we'll see. So this is made for everything from the fat PS4 to the Slim to the Pro. So if you have a Slim, it drops in here but if we have the Pro, we should just be able to get it in something like this. Actually, it fits pretty well. So there's nothing really holding it in besides friction. On the bottom, we do have those, wait what? It's really only pulling a little bit of air from here. I mean, they look like reasonable sized fans but how is that gonna drive any significant airflow into the PS4? Next up, we have something a little bit more simple. This is a PS4 USB hub. So as the name suggests, it's pretty straightforward. It turns the two USB ports on the front of the PS4 into five. So this is specifically made for the fat PS4. So in the back, we have a pair of USB ports and on the front, we have one USB 3, which is a pass-through, and four standard USB 2. It should be pretty much as simple as just lining it up and that's it. Again, I appreciate how well this actually fits with the original design, so even with this and the intercooler, it doesn't really look like a Frankenstein. I mean, at least not yet. Now it's time for the big guns. This is the DongCoh Game Bar. Now that name doesn't really tell you much, but what this is going to allow you to do is install a full desktop hard drive into your PS4. Infinity storage, super speed, dissipation, and stability. Man, I am excited for this one. Oh boy, here we go. Oh that looks like a lot. So this is going to require just a little bit of surgery on our PS4. However, it's not going to be bad. So the PS4, as well as the PS4 Slim, PS4 Pro, all have removable hard drives. So what this is going to allow us to do is instead of using a small 2.5 inch drive like from a laptop, to actually use a full desktop drive. This is feeling like a dumber and dumber idea each second. So essentially, this should kind of go and replace this top piece. So this glossy piece right here just pops right off and inside, normally, you would just replace the hard drive here. However, it's gonna be a little bit more involved with this guy. So to start, we're gonna take out the puny 500-gigabyte hard drive in favor of something just a little bit beefier. So to really go all out, we're upgrading this with a four-terabyte hard drive. However, this actually supports up to six terabytes if you really need all the storage you can. On top of that, they actually just announced a new PS4 firmware update that will allow you to actually put games on external USB drives. So if you really wanna get crazy with it, you could put a ton of storage in your PS4. So I just need to set the SATA cable in like that and I can close the whole thing up. So all this is is really just a pass-through. So once we're ready, we just slide it into the standard PS4 slot and screw it in. Alright, here goes nothing. So we want to run all of our power and data through this little slot. Get around here. Okay, that actually kinda works. Now we just need to drop the hard drive in like this and doesn't seem very stable, but besides that, we just have to attach the cable and in theory, we pretty much have a four-terabyte PS4. Uh-oh. It totally fits. (laughs) We have created a monster. Dude, if this is about to work, I'm gonna be so happy. It totally fits! This is, I gotta say, this might be the proudest moment of my entire life, this is a masterpiece of elegant Japanese engineering, or it's all Ken's fault. So one quick firmware update later, we have the ultimate Frankenstein PS4 up and running, and as you can hear, it's kind of loud. We also have the Energizer Xtra Life for the controller. So this is a dock that comes with an external battery that clips on the bottom of the controller so it doesn't really get in the way when you're actually playing a game. First thing, I wanna check to see if our storage is here so yep, there we go, 3.51 terabytes of free space. Now, with so many PS4s shipping with a 500-gigabyte hard drive, it can really get cramped quickly. So this is Uncharted 4 and it looks, well, exactly like Uncharted 4. So what I'm curious about are the temperatures. I can pretty confidently say that this is louder than a normal PS4, but I'm curious whether that loudness actually does anything. So the PS4 with the intercooler and the cooling stand topped out around 49 degrees with the exhaust. However, when you take all that stuff off and run it, it tops out at about 50. That shouldn't be a huge surprise. So the intercooler is just adding additional fans for the exhaust, it's still restricted by how much intake air can actually get into the PS4. Now the cooling stand in theory would actually help things by giving it some fresh air. However, the actual intakes themselves are tiny and really not able to make a big difference. So is any of this worth it? Kind of. So first of all, the Energizer Xtra Life dock is actually not bad. The dock itself is clean, but most importantly, the battery doesn't get in the way, it legitimately does give you extra time on the PS4. Which brings us to the Game Bar. So on one hand, it actually works really well. Once you get past the setup, it's completely seamless, and if you really do need four or six terabytes of storage with your PS4, then it's kind of a no-brainer. However, if you don't need that much storage, it's a lot easier to just install a one- or two-terabyte hard drive, and on top of that, the update to allow you to put games on a USB drive is coming soon. I do really like the USB hub. So with the PS4 only having two USB ports, especially if you have something like PlayStation VR set up, those ports disappear quickly. Which brings us to the intercooler and the cooling stand. Don't buy these. The intercooler, while it actually does integrate pretty well and doesn't really hurt anything, I'm not convinced it actually makes difference whatsoever. Now the stand does give you a few options like being able to dock your controllers, as well as in theory giving you a little bit more cooling, but again, I don't really believe it's actually making any significant difference. As always, all the links you guys need to any of this stuff will be in the description if you wanna go check it out, and I'm curious, what do you think about this monstrosity? Let me know in the comments below and I will catch you in the next one."
GetTextAndTranslate(bearer_token, "fr", to_trans)
Example #7
0
from auth import AzureAuthClient
from ws4py.client.threadedclient import WebSocketClient
import uuid
import MessageFactory
import AudioStreamer
import json

client_secret = '7c8dbb5b479847d0b840102d13cc348a'
ws_url = "wss://speech.platform.bing.com/speech/recognition/interactive/cognitiveservices/v1?format=simple&language=de-DE"
auth_client = AzureAuthClient(client_secret)


class SpeechToTextClient(WebSocketClient):
    def __init__(self, stoppedCallback):
        self.stoppedCallback = stoppedCallback

        super(SpeechToTextClient,
              self).__init__(ws_url,
                             headers=[
                                 ('Authorization',
                                  'Bearer ' + auth_client.get_access_token()),
                                 ('X-ClientTraceId', uuid.uuid4())
                             ])

    def opened(self):
        print "Connected!"
        self.connected = True
        MessageFactory.connectionEstablished()
        self.sendConfigMessage()
        self.audioStreamer = AudioStreamer.AudioStreamer(self)
        self.audioStreamer.start()
    textToTranslate = raw_input("Type the text that you want to translate:  ")

    print " "

    # Call to Microsoft Translator Service
    headers = {"Authorization ": finalToken}
    translateUrl = "http://api.microsofttranslator.com/v2/Http.svc/Translate?text={}&to={}".format(textToTranslate, toLangCode)

    translationData = requests.get(translateUrl, headers = headers)
    # parse xml return values
    translation = ElementTree.fromstring(translationData.text.encode('utf-8'))
    # display translation
    print "The translation is---> ", translation.text

    print " "


if __name__ == "__main__":
    client_secret = open("client_secret.txt").readline().strip()

    #client_secret = 'ENTER_YOUR_CLIENT_SECRET'
    auth_client = AzureAuthClient(client_secret)
    bearer_token = 'Bearer ' + auth_client.get_access_token()

    while (doItAgain == 'yes') or (doItAgain == 'Yes'):
        GetTextAndTranslate(bearer_token)
        print ' '
        doItAgain = raw_input('Type yes to translate more, any other key to end: ')

    goodBye = raw_input('Thank you for using Microsoft Translator, we appreciate it. Good Bye')
Example #9
0
    def __next__(self):
        if not self.eof_reached:
            data = self.input.readframes(self.chunk_size)
            if len(data) > 0:
                return data
            self.eof_reached = True
        if self.silence_duration > 0:
            self.silence_duration -= self.chunk_length
            return self.silence_chunk
        raise StopIteration


if __name__ == "__main__":

    client_secret = 'fb4555930a7b49b2abd2db40c66ab275'
    auth_client = AzureAuthClient(client_secret)

    # Audio file(s) to transcribe
    audio_file = '/Users/zhangjiwang/PycharmProjects/AI-Learning/samples/speech-translator/tts_1.wav'
    audio_source = WaveFileAudioSource(audio_file, 100, 2000)
    # Translate from this language. The language must match the source audio.
    # Supported languages are given by the 'speech' scope of the supported languages API.
    translate_from = 'fr'
    # Translate to this language.
    # Supported languages are given by the 'text' scope of the supported languages API.
    translate_to = 'ja'
    # Features requested by the client.
    features = "Partial,TextToSpeech"

    voice = 'ja-JP-Ayumi'
Example #10
0
def main(filename):
    client_secret = 'XXXXXX'
    auth_client = AzureAuthClient(client_secret)

    # Audio file(s) to transcribe
    audio_file = filename
    audio_source = WaveFileAudioSource(audio_file, 100, 2000)
    # Translate from this language. The language must match the source audio.
    # Supported languages are given by the 'speech' scope of the supported languages API.
    translate_from = 'en-US'
    # Translate to this language.
    # Supported languages are given by the 'text' scope of the supported languages API.
    translate_to = 'es'
    # Features requested by the client.
    features = "TextToSpeech"

    # Transcription results will be saved into a new folder in the current directory
    output_folder = os.path.join(os.getcwd(), uuid.uuid4().hex)

    # These variables keep track of the number of text-to-speech segments received.
    # Each segment will be saved in its own audio file in the output folder.
    tts_state = {'count': 0}

    # Setup functions for the Websocket connection

    def on_open(ws):
        """
        Callback executed once the Websocket connection is opened.
        This function handles streaming of audio to the server.

        :param ws: Websocket client.
        """

        #print 'Connected. Server generated request ID = ', ws.sock.headers['x-requestid']

        def run(*args):
            """Background task which streams audio."""

            # Send WAVE header to provide audio format information
            data = get_wave_header(audio_source.getframerate())
            ws.send(data, websocket.ABNF.OPCODE_BINARY)
            # Stream audio one chunk at a time
            for data in audio_source:
                sys.stdout.write('.')
                ws.send(data, websocket.ABNF.OPCODE_BINARY)
                time.sleep(0.1)

            audio_source.close()
            ws.close()
            #print 'Background thread terminating...'

        thread.start_new_thread(run, ())

    def on_close(ws):
        """
        Callback executed once the Websocket connection is closed.

        :param ws: Websocket client.
        """
        #print 'Connection closed...'

    def on_error(ws, error):
        """
        Callback executed when an issue occurs during the connection.

        :param ws: Websocket client.
        """
        #print error

    def on_data(ws, message, message_type, fin):
        """
        Callback executed when Websocket messages are received from the server.

        :param ws: Websocket client.
        :param message: Message data as utf-8 string.
        :param message_type: Message type: ABNF.OPCODE_TEXT or ABNF.OPCODE_BINARY.
        :param fin: Websocket FIN bit. If 0, the data continues.
        """
        global resultjson
        global texttranslated
        if message_type == websocket.ABNF.OPCODE_TEXT:
            #print '\n', message, '\n'
            resultjson = json.loads(message)
            #print type(msgjson)
            #textinaudio= msgjson['recognition']
            #texttranslated = msgjson['translation']
        else:
            tts_count = tts_state['count']
            tts_file = tts_state.get('file', None)
            if tts_file is None:
                tts_count += 1
                tts_state['count'] = tts_count
                fname = "tts_{0}.wav".format(tts_count)
                #print "\nTTS segment #{0} begins (file name: '{1}').\n".format(tts_count, fname)
                if not os.path.exists(output_folder):
                    os.makedirs(output_folder)
                tts_file = open(os.path.join(output_folder, fname), 'wb')
                tts_state['file'] = tts_file
            tts_file.write(message)
            if fin:
                #print '\n', "TTS segment #{0} ends.'.".format(tts_count), '\n'
                tts_file.close()
                del tts_state['file']
    client_trace_id = str(uuid.uuid4())
    request_url = "wss://dev.microsofttranslator.com/speech/translate?from={0}&to={1}&features={2}&api-version=1.0".format(translate_from, translate_to, features)

    print "Ready to connect..."
    print "Request URL      = {0})".format(request_url)
    print "ClientTraceId    = {0}".format(client_trace_id)
    #print 'Results location = %s\n' % (output_folder)

    ws_client = websocket.WebSocketApp(
        request_url,
        header=[
            'Authorization: Bearer ' + auth_client.get_access_token(),
            'X-ClientTraceId: ' + client_trace_id
        ],
        on_open=on_open,
        on_data=on_data,
        on_error=on_error,
        on_close=on_close
    )
    ws_client.run_forever()
    return resultjson
Example #11
0
 def _GetMicrosoftAuthToken(self):
     auth_client = AzureAuthClient(self.microsoft_translator_client_secret)
     access_token = auth_client.get_access_token()
     return "Bearer " + access_token.decode(self.Character_Encoding)