def wlhome(): # This is how you do logging, in this case information messages. app.logger.info('wlhome page requested') allinfo = {} lang = 'TBD' txt = None form = LangForm() # If the form passes this check, then its a POST and the fields are valid. # ie. if the request is a GET then this check fails. if form.validate_on_submit(): lang = 'TBC' txt = form.txtdata.data form.txtdata.data = '' try: language_translation = \ LanguageTranslation(username=username, password=password) langsdetected = language_translation.identify(txt) primarylang = langsdetected["languages"][0] lang = \ "I am {confidence} confident that the language is {language}." lang = lang.format(**primarylang) session['langtext'] = lang allinfo['lang'] = lang allinfo['form'] = form return redirect(url_for('wlhome')) except WatsonException as err: allinfo['error'] = err allinfo['lang'] = session.get('langtext') allinfo['form'] = form return render_template('watson/wlindex.html', info=allinfo)
def hello_world(): cluster = Cluster(['172.17.0.2']) session = cluster.connect() session.execute("CREATE KEYSPACE IF NOT EXISTS results WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};") session.execute("USE results;") session.execute("create table IF NOT EXISTS result_table(translate_source text,translate_result text,analyze_result text,result_id text PRIMARY KEY);") language_translation = LanguageTranslation( username='******', password='******') f = open('translate_file.txt',"r") line = f.readline() translation = language_translation.translate( text=line, source='fr', target='en') translated_text = json.dumps(translation, indent=2, ensure_ascii=False) tone_analyzer = ToneAnalyzerV3( username='******', password='******', version='2016-05-19 ') analyze = json.dumps(tone_analyzer.tone(text=translated_text), indent=2) session.execute("INSERT INTO result_table (translate_source,translate_result,analyze_result,result_id) VALUES(%s,%s,%s,%s)",(line,translated_text,analyze,1)) session.execute("SELECT * FROM result_table;") return(analyze)
def index(request): allinfo = {} form = None if request.POST: form = Form_language(request.POST) if form.is_valid(): data = form.cleaned_data['txtdata'] logger.info("Text to be process is %s" % data) lang = "TBD" try: language_translation = LanguageTranslation( username= '******', password='******') langsdetected = language_translation.identify(data) primarylang = langsdetected["languages"][0]['language'] confidence = langsdetected["languages"][0]['confidence'] lang = "I am %s confident that the language is %s" % ( confidence, primarylang) except WatsonException as err: allinfo['error'] = err allinfo['lang'] = lang else: allinfo['error'] = "The form is invalid" else: form = Form_language allinfo['form'] = form return render(request, 'watson/wlindex.html', allinfo)
def wlhome(): # This is how you do logging, in this case information messages. app.logger.info('wlhome page requested') allinfo = {} lang = "TBD" txt = None form = LangForm() # If the form passes this check, then its a POST and the fields are valid. ie. if the # request is a GET then this check fails. if form.validate_on_submit(): lang = "TBC" txt = form.txtdata.data form.txtdata.data = '' try: language_translation = LanguageTranslation(username='******', password='******') langsdetected = language_translation.identify(txt) primarylang = langsdetected["languages"][0]['language'] confidence = langsdetected["languages"][0]['confidence'] lang = "I am %s confident that the language is %s" % (confidence, primarylang) session['langtext'] = lang allinfo['lang'] = lang allinfo['form'] = form return redirect(url_for('wlhome')) except WatsonException as err: allinfo['error'] = err allinfo['lang'] = session.get('langtext') allinfo['form'] = form return render_template('watson/wlindex.html', info=allinfo)
def Image_design(): visual_recognition = VisualRecognitionV3( '2016-05-20', api_key='1c5c0cf7321c6c8712c162f7b2153ae69364c974') with open(join(dirname(__file__), '11.png'), 'rb') as image_file: vs = json.dumps( visual_recognition.recognize_text(images_file=image_file), indent=2) text1 = json.loads(vs) text1 = text1["images"][0]["text"] text1 = json.dumps(text1, indent=2) text1 = text1.replace('\\n', ' ') text1 = text1.replace('\"', ' ') language_translation = LanguageTranslation( username='******', password='******') translation = language_translation.translate(text=text1, source='en', target='es') eslang = translation tone_analyzer = ToneAnalyzerV3( username='******', password='******', version='2016-05-19 ') tone = tone_analyze(text1) do_with_cassandra(vs, text1, eslang, tone) return '<p>IMAGE IDENTIFY: ' + vs + '</p>' + '<p>Spanish: ' + eslang + '</p>' + '<p>English: ' + text1 + '</p>' + '<p>TONE: ' + tone + '</p>'
def getTranslationService(): ''' Args: None Returns: LanguageTranslation (class): this is just a wrapper for the service credentials ''' return LanguageTranslation(username=username, password=password)
def login(): tone_analyzer = ToneAnalyzerV3( username='******', password='******', version='2016-05-19 ') text = json.dumps(request.get_json()["text"]) id = int(json.dumps(request.get_json()["id"])) res = tone_analyzer.tone(text) a = (json.dumps(tone_analyzer.tone(text), indent=2)) language_translation = LanguageTranslation( username='******', password='******') tone = [] score = [] for i in range(3): tone.append( language_translation.translate( text=res["document_tone"]["tone_categories"][0]["tones"][i] ["tone_name"], source='en', target='fr')) score.append( res["document_tone"]["tone_categories"][0]["tones"][i]["score"]) #b=b.encode("utf-8") #c=c.encode("utf-8") cluster = Cluster(['172.17.0.2']) session = cluster.connect() session.execute( """create keyspace demo3 with replication={'class':'SimpleStrategy','replication_factor':'1'};""" ) session.execute("""use demo3""") session.execute( "create table users(tone_name text ,score float,tone_id int, primary key(tone_id))" ) prepared_stmt = session.prepare( "INSERT INTO users (tone_name,score,tone_id) VALUES (?, ?, ?)") for i in range(3): bound_stmt = prepared_stmt.bind([tone[i], score[i], (id * 10 + i + 1)]) stmt = session.execute(bound_stmt) #session.execute("""insert into demo2.users(id,input)values(request.args.get("id"),request.args.get("text"));""") ##session.execute("create table demo.users(tone_name text primary key,score float,tone_id text)") #session.execute("""insert into demo.users(tone_name,score,tone_id)values('Anger',a["document_tone"]["tone_categories"]["tones"]["score"],'anger');""") #session.execute("""insert into demo.users(tone_name,score,tone_id)values('Disgust',a["document_tone"]["tone_categories"]["tones"]["score"],'disgust');""") #session.execute("""insert into demo.users(tone_name,score,tone_id)values('Happy',0.2082342,'happy');""") #session.execute("""select * from users;""") translation = "id\ttone\tscore\t\n" + str( id * 10 + 1) + "\t" + tone[0] + "\t" + str( score[0]) + "\n" + str(id * 10 + 2) + "\t" + tone[1] + "\t" + str( score[1]) + "\n" + str(id * 10 + 3) + "\t" + tone[2] + "\t" + str( score[2]) return translation
def translate(text_to_translate): language_translation = LanguageTranslation( version='2018-05-01', iam_apikey='0W0AoUw-0Yxg11L5DmNPFPbwMM7De0vT-5IeTyrES-co') translation = language_translation.translate(text=text_to_translate, source='en', target='fr') # return translation['result'] return translation.result['translations'][0]['translation']
def translations(trantext): language_translation = LanguageTranslation( username='******', password='******') translation1 = language_translation.translate( text=trantext, source='en', target='es') return translation1
def translation(): language_translation = LanguageTranslation( username='******', password='******') f1 = open('trans.txt','r') content1 = f1.read() eslang = language_translation.translate( text=content1, source='en', target='es') return '<p>CONTENT: '+content1+'</p>'+'<p>TRANLATION: '+eslang+'</p>'
def hello_world(): #This part is to connect to the cassandra cluster = Cluster(['172.17.0.2']) session = cluster.connect() #Create the table in cassadra that we will need. session.execute( "CREATE KEYSPACE IF NOT EXISTS results WITH replication = {'class':'SimpleStrategy', 'replication_factor' : 3};" ) session.execute("USE results;") session.execute( "create table IF NOT EXISTS result_table(translate_source text,translate_result text,analyze_result text,result_id text PRIMARY KEY);" ) #This part is to use one API of the Languge Translation service language_translation = LanguageTranslation( username='******', password='******') #Read the content from a text file that you want to translate f = open('translate_file.txt', "r") line = f.readline() translation = language_translation.translate(text=line, source='fr', target='en') #We get the translated text translated_text = json.dumps(translation, indent=2, ensure_ascii=False) #This part is to use one API of the Tone Analyzer service tone_analyzer = ToneAnalyzerV3( username='******', password='******', version='2016-05-19 ') analyze = json.dumps(tone_analyzer.tone(text=translated_text), indent=2) #Put the origin text,translated text, and analyzed text into the table we created. session.execute( "INSERT INTO result_table (translate_source,translate_result,analyze_result,result_id) VALUES(%s,%s,%s,%s)", (line, translated_text, analyze, '1')) session.execute("SELECT * FROM result_table;") return analyze
# coding=utf-8 import json from watson_developer_cloud import LanguageTranslationV2 as LanguageTranslation language_translation = LanguageTranslation(username='******', password='******') print(json.dumps(language_translation.get_models(), indent=2)) print( json.dumps(language_translation.translate('Hola, cómo estás? €', source='es', target='en'), indent=2, ensure_ascii=False)) print(json.dumps(language_translation.identify('Hello how are you?'), indent=2))
import json import random from watson_developer_cloud import LanguageTranslationV2 as LanguageTranslation languagecodes = ['ar', 'es', 'fr', 'it', 'pt'] language_translation = LanguageTranslation( username='******', password='******') prevlanguage = 'en' translation = raw_input("Text to translate: ") for i in range(10): language = random.choice(languagecodes) print language translation = language_translation.translate(text=translation, source='en', target=language) print(translation) translation = language_translation.translate(text=translation, source=language, target='en') print(translation) prevlanguage = language #finaltranslation=language_translation.translate(text=translation, source=prevlanguage, target='en') #print(finaltranslation)