0.1.2 change help display, remove alternative url

This commit is contained in:
Nestero 2022-01-11 00:23:19 +07:00
parent d6eba3b84b
commit 387d3e0af2
5 changed files with 125 additions and 47 deletions

View File

@ -10,21 +10,24 @@ pip install pylingva
## CLI
```shell
$ translate -h
usage: translate [-h] [-s SOURCE] [-t TARGET] [-txt TEXT] [-ll] [-f FILE] [-o OUTPUT]
options:
-h, --help show this help message and exit
-s SOURCE, --source SOURCE
Source Language to translate
-t TARGET, --target TARGET
Target Language to translate
-txt TEXT, --text TEXT
Text to translate
-ll, --list-languages
List Languages support
-f FILE, --file FILE Path file .txt to translate
-o OUTPUT, --output OUTPUT
Output file translation result
██████╗ ██╗ ██╗██╗ ██╗███╗ ██╗ ██████╗ ██╗ ██╗ █████╗
██╔══██╗╚██╗ ██╔╝██║ ██║████╗ ██║██╔════╝ ██║ ██║██╔══██╗
██████╔╝ ╚████╔╝ ██║ ██║██╔██╗ ██║██║ ███╗██║ ██║███████║
██╔═══╝ ╚██╔╝ ██║ ██║██║╚██╗██║██║ ██║╚██╗ ██╔╝██╔══██║
██║ ██║ ███████╗██║██║ ╚████║╚██████╔╝ ╚████╔╝ ██║ ██║
╚═╝ ╚═╝ ╚══════╝╚═╝╚═╝ ╚═══╝ ╚═════╝ ╚═══╝ ╚═╝ ╚═╝
Simple translator tool.
Options:
-h, --help Display this message
-s, --source Source Language to translate
-t, --target Target Language to translate
-txt, --text Text to translate
-ll, --list-languages List Languages support
-f, --file Path file .txt to translate
-o, --output Output file translation result
$ translate -s auto -t id -txt "How are You ?"
Apa kabar ?

67
pylingva/arg.py Normal file
View File

@ -0,0 +1,67 @@
#! /usr/bin/env python
import os
import sys
import argparse, textwrap
class ArgumentParser(argparse.ArgumentParser):
def __init__(self, *args, **kwargs):
super(ArgumentParser, self).__init__(*args, **kwargs)
self.program = { key: kwargs[key] for key in kwargs }
self.options = []
def add_argument(self, *args, **kwargs):
super(ArgumentParser, self).add_argument(*args, **kwargs)
option = {}
option["flags"] = [ item for item in args ]
for key in kwargs:
option[key] = kwargs[key]
self.options.append(option)
def print_help(self):
wrapper = textwrap.TextWrapper(width=80)
# Print usage
# if "usage" in self.program:
# print("Usage: %s" % self.program["usage"])
# else:
# usage = []
# for option in self.options:
# usage += [ "[%s %s]" % (item, option["metavar"]) if "metavar" in option else "[%s %s]" % (item, option["dest"].upper()) if "dest" in option else "[%s]" % item for item in option["flags"] ]
# wrapper.initial_indent = "Usage: %s " % os.path.basename(sys.argv[0])
# wrapper.subsequent_indent = len(wrapper.initial_indent) * " "
# output = str.join(" ", usage)
# output = wrapper.fill(output)
# print(output)
# print()
# Print description
if "description" in self.program:
print(self.program["description"])
print()
# Print options
print("Options:")
maxlen = 0
for option in self.options:
option["flags2"] = str.join(", ", [ "%s %s" % (item, option["metavar"]) if "metavar" in option else "%s %s" % (item, option["dest"].upper()) if "dest" in option else item for item in option["flags"] ])
if len(option["flags2"]) > maxlen:
maxlen = len(option["flags2"])
for option in self.options:
template = " %-" + str(maxlen) + "s "
wrapper.initial_indent = template % option["flags2"]
wrapper.subsequent_indent = len(wrapper.initial_indent) * " "
if "help" in option and "default" in option:
output = option["help"]
output += " (default: '%s')" % option["default"] if isinstance(option["default"], str) else " (default: %s)" % str(option["default"])
output = wrapper.fill(output)
elif "help" in option:
output = option["help"]
output = wrapper.fill(output)
elif "default" in option:
output = "Default: '%s'" % option["default"] if isinstance(option["default"], str) else "Default: %s" % str(option["default"])
output = wrapper.fill(output)
else:
output = wrapper.initial_indent
print(output)

View File

@ -1,10 +1,20 @@
#! /usr/bin/env python
from pylingva.arg import ArgumentParser
from pylingva import pylingva
import argparse
desc = """
Simple translator tool.
"""
def translate():
arg = argparse.ArgumentParser()
arg = ArgumentParser(description=desc, allow_abbrev=False, add_help=False)
arg.add_argument("-h", "--help", action="help", help="Display this message")
arg.add_argument("-s", "--source", type=str, help="Source Language to translate")
arg.add_argument("-t", "--target", type=str, help="Target Language to translate")
arg.add_argument("-txt", "--text", type=str, help="Text to translate")

View File

@ -5,38 +5,36 @@ import requests as req
class pylingva:
def __init__(self):
self.url_list = ("https://lingva.ml", "https://translate.alefvanoon.xyz", "https://translate.igna.rocks", "https://lingva.pussthecat.org")
for url in self.url_list:
url = "https://lingva.ml"
try:
check_url = req.get(url)
status = check_url.status_code
if status == 200:
self.url = url + "/api/v1/"
break
else:
self.url = 0
check_url.raise_for_status()
self.url = url + "/api/v1/"
except req.exceptions.RequestException as er:
print(er)
exit()
except req.exceptions.ConnectionError as er:
print(er)
exit()
except req.exceptions.Timeout as er:
print(er)
exit()
def languages(self):
if self.url == 0:
print("Server Down !")
else:
url = self.url + "languages"
all_languages = req.get(url)
all_languages = all_languages.json()
lang = {}
for x in range(0, len(all_languages['languages'])):
list_code = all_languages['languages'][x]['code']
list_name = all_languages['languages'][x]['name']
lang.update({list_name: list_code})
return lang
url = self.url + "languages"
all_languages = req.get(url)
all_languages = all_languages.json()
lang = {}
for x in range(0, len(all_languages['languages'])):
list_code = all_languages['languages'][x]['code']
list_name = all_languages['languages'][x]['name']
lang.update({list_name: list_code})
return lang
def translate(self, source, target, text):
if self.url == 0:
print("Server Down !")
else:
url = f"{self.url}/{source}/{target}/{text}"
url = url.replace("?", "%3F")
r = req.get(url)
r = r.json()
result = r['translation']
return result
url = f"{self.url}/{source}/{target}/{text}"
url = url.replace("?", "%3F")
r = req.get(url)
r = r.json()
result = r['translation']
return result

View File

@ -7,7 +7,7 @@ with open("README.md", "r") as des:
setup(
name='pylingva',
packages=find_packages(),
version='0.1.1',
version='0.1.2',
entry_points={'console_scripts': ['translate = pylingva.cli:translate']},
description='Simple translator using Lingva Translate API',
url='https://gitlab.com/nesstero/pylingva',