Esempio n. 1
0
def get_flat_meanings(text, target_lang):
    source_lang = translator.detect_language(text)
    translation = translator.translate(text, target_lang, source_lang)

    dict_dir = source_lang + '-' + target_lang
    response = requests.get(
        (settings.YA_TRANSLATOR['URL'] + '&lang=%(dictDir)s&text=%(text)s') % {
            'yaDictKey': settings.YA_TRANSLATOR['KEY'],
            'dictDir': dict_dir,
            'text': text
        })
    ya_dict = response.json()

    meanings = set()
    meanings.add(translation.lower())
    if len(ya_dict['def']):
        for yaDef in ya_dict['def']:
            for yaDefTr in yaDef['tr']:
                meaning = yaDefTr['text'].lower()
                meanings.add(meaning)
                if 'syn' in yaDefTr:
                    for yaDefTrSyn in yaDefTr['syn']:
                        meaning = yaDefTrSyn['text'].lower()
                        meanings.add(meaning)

    return meanings
Esempio n. 2
0
    def get(self, request):
        """
        ---
        parameters:
            - name: string
              description: a string to translate
              required: true
              type: string
              paramType: query
            - name: lang
              description: a target language
              required: true
              type: string
              paramType: query
        """
        text = self.get_text(request)
        target_lang = self.get_lang(request)

        history_serializer = self.init_history_serializer(request, text)
        history_serializer.is_valid(raise_exception=True)
        history_serializer.save(user=request.user)

        source_lang = translator.detect_language(text)
        translation = ''

        ya_translation_direction = source_lang + '-' + target_lang
        ya_url = (settings.YA_TRANSLATOR['URL'] + '&lang=%(dictDir)s&text=%(text)s') % \
                 {
                     'yaDictKey': settings.YA_TRANSLATOR['KEY'],
                     'dictDir': ya_translation_direction,
                     'text': text
                 }

        ya_response = requests.get(ya_url)

        if ya_response.status_code != status.HTTP_200_OK or len(ya_response.json()['def']) == 0:
            translation = translator.translate(text, target_lang, source_lang)

        response = {
            'translation_history': history_serializer.data,
            'translation': translation,
            'ya_dict': ya_response.json()
        }

        if ya_response.status_code == status.HTTP_200_OK:
            response['ya_dict'] = ya_response.json()
        else:
            response['ya_dict'] = {}

        card_serializer = self.init_card_serializer(request, text)

        if card_serializer is not None:
            response['card'] = card_serializer.data

        return Response(response, status=status.HTTP_200_OK)