-
Notifications
You must be signed in to change notification settings - Fork 0
/
lab_7_step_5_input_validation.py
77 lines (66 loc) · 2.61 KB
/
lab_7_step_5_input_validation.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# Standard Imports
import argparse
import json
# 3rd Party Imports
import boto3
# Arguments
parser = argparse.ArgumentParser(description="Provides translation between one source language and another of the same set of languages.")
parser.add_argument(
'--file',
dest='filename',
help="The path to the input file. The file should be valid json",
required=True
)
args = parser.parse_args()
# Functions
# Open the input file to get the json.
def open_input():
with open(args.filename) as file_object:
contents = json.load(file_object)
return contents['Input']
# Boto3 function to use Amazon Translate to translate the text and only return the Translated Text
def translate_text(**kwargs):
client = boto3.client('translate')
response = client.translate_text(**kwargs)
print(response['TranslatedText'])
# Add a Loop to iterate over the json file.
def translate_loop():
input_text = open_input()
for item in input_text:
if input_validation(item) == True:
translate_text(**item)
else:
raise SystemError
# Add our input validation as a function here.
def input_validation(item):
languages = ["af","sq","am","ar","az","bn","bs","bg","zh","zh-TW","hr","cs","da","fa-AF",
"nl","en","et","fi","fr","fr-CA","ka","de","el","ha","he","hi","hu","id","it",
"ja","ko","lv","ms","no","fa","ps","pl","pt","ro","ru","sr","sk","sl","so","es",
"sw","sv","tl","ta","th","tr","uk","ur","vi"
]
json_input=item
SourceLanguageCode = json_input['SourceLanguageCode']
TargetLanguageCode = json_input['TargetLanguageCode']
if SourceLanguageCode == TargetLanguageCode:
print("The SourceLanguageCode is the same as the TargetLanguageCode - nothing to do")
return False
elif SourceLanguageCode not in languages and TargetLanguageCode not in languages:
print("Neither the SourceLanguageCode and TargetLanguageCode are valid - stopping")
return False
elif SourceLanguageCode not in languages:
print("The SourceLanguageCode is not valid - stopping")
return False
elif TargetLanguageCode not in languages:
print("The TargetLanguageCode is not valid - stopping")
return False
elif SourceLanguageCode in languages and TargetLanguageCode in languages:
print("The SourceLanguageCode and TargetLanguageCode are valid - proceeding")
return True
else:
print("There is an issue")
return False
# Main Function - use to call other functions
def main():
translate_loop()
if __name__ == "__main__":
main()