Skip to content

Commit

Permalink
Add files via upload
Browse files Browse the repository at this point in the history
  • Loading branch information
PetitPotiron authored Oct 10, 2021
1 parent 66850b9 commit ced4cd3
Show file tree
Hide file tree
Showing 6 changed files with 109 additions and 39 deletions.
2 changes: 1 addition & 1 deletion __init__.py
Original file line number Diff line number Diff line change
@@ -1 +1 @@
from .client import *
from .client import *
2 changes: 1 addition & 1 deletion __version__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,4 +4,4 @@
__version__ = '1.0.0'
__author__ = 'PetitPotiron'
__license__ = 'GNU General Public License v3.0'
__copyright__ = 'Copyright (c) 2021 PetitPotiron'
__copyright__ = 'Copyright (c) 2021 PetitPotiron'
65 changes: 38 additions & 27 deletions client.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,25 @@
from os import PathLike
import base64
import urllib.request as request
import json
import time
import os.path as path
from .conversion import *
from .options import *
import urllib.error as weberror
import urllib.request as request
from typing import Any, Optional

from convertio.types import ConversionPostDict, ConversionPostDictOptions, ConversionPostResult, ConversionStatusResult

class Client:
from .conversion import Conversion
from .options import Options

def __init__(self, token) -> None:

class Client:
def __init__(self, token: str) -> None:
self.token = token

def convert_by_filename(self, fp: PathLike, output_format: str, output_filename: str = None, options: Options = None):
def convert_by_filename(self,
fp: str,
output_format: str,
output_filename: Optional[str] = None,
options: Optional[Options] = None) -> Any:
"""Converts the file found in the path provided.
Args:
Expand All @@ -26,8 +31,9 @@ def convert_by_filename(self, fp: PathLike, output_format: str, output_filename:
filename = "".join(path.splitext(path.basename(fp)))
else:
filename = output_filename

if options is not None:
_options = {
_options: Optional[ConversionPostDictOptions] = {
'ocr_enabled': True,
'ocr_settings': {
'langs': options.langs,
Expand All @@ -36,15 +42,17 @@ def convert_by_filename(self, fp: PathLike, output_format: str, output_filename:
}
else:
_options = None

with open(fp, 'r') as file:
data = {
data: ConversionPostDict = {
'apikey': self.token,
'input': 'base64',
'file': base64.b64encode(file.read().encode('utf8')).decode('utf8'),
'filename': filename,
'outputformat': output_format,
'options': _options
}

if data['options'] is None:
del data['options']
else:
Expand All @@ -53,6 +61,7 @@ def convert_by_filename(self, fp: PathLike, output_format: str, output_filename:

if data['options']['ocr_enabled'] is False:
del data['options']

r = request.Request(
url='https://api.convertio.co/convert',
data=json.dumps(data).encode("utf8"),
Expand All @@ -61,8 +70,8 @@ def convert_by_filename(self, fp: PathLike, output_format: str, output_filename:
r.add_header('Content-Type', 'application/json')
try:
r = request.urlopen(r)
data = json.loads(r.read().decode('utf8'))
return data['data']['id']
result: ConversionPostResult = json.loads(r.read().decode('utf8'))
return result['data']['id']
except weberror.HTTPError as e:
if e.code == 401:
raise ValueError(
Expand All @@ -73,15 +82,15 @@ def convert_by_filename(self, fp: PathLike, output_format: str, output_filename:
raise ValueError(
'CONVERTER: The Type of Output File is not supported yet')

def convert_by_url(self, url: str, output_format: str, options: Options = None):
def convert_by_url(self, url: str, output_format: str, options: Optional[Options] = None) -> Optional[str]:
"""Converts the file found in the given url.
Args:
url (str): The url where the file is
output_format (str): The file format you want the file to be converted to
options (Options, optional): OCR Options Defaults to None.
"""
data = {
data: ConversionPostDict = {
'apikey': self.token,
'input': 'url',
'file': url,
Expand All @@ -91,9 +100,10 @@ def convert_by_url(self, url: str, output_format: str, options: Options = None):
'ocr_settings': {
'langs': options.langs,
'page_nums': options.page_nums
} if options else None,
},
} if options else None
}

if data['options'] is None:
del data['options']
else:
Expand All @@ -110,8 +120,8 @@ def convert_by_url(self, url: str, output_format: str, options: Options = None):
r.add_header('Content-Type', 'application/json')
try:
r = request.urlopen(r)
data = json.loads(r.read().decode('utf8'))
return data['data']['id']
result: ConversionPostResult = json.loads(r.read().decode('utf8'))
return result['data']['id']
except weberror.HTTPError as e:
if e.code == 401:
raise ValueError(
Expand All @@ -135,15 +145,15 @@ def check_conversion(self, id: str):
r = request.Request(f'https://api.convertio.co/convert/{id}/status')
try:
r = request.urlopen(r)
data = json.loads(r.read().decode('utf8'))
return Conversion(data)
result: ConversionStatusResult = json.loads(r.read().decode('utf8'))
return Conversion(result)
except weberror.HTTPError as e:
if e.code == 404:
raise ValueError("The system is unable to find the requested action (the conversion isn't found)")
elif e.code == 422:
raise ValueError('Input file appears to be corrupted')

def download(self, id: str, fp: PathLike):
def download(self, id: str, fp: str) -> None:
"""Writes the file content to a path."""
r = request.Request(f'https://api.convertio.co/convert/{id}/status')
try:
Expand All @@ -157,23 +167,24 @@ def download(self, id: str, fp: PathLike):

with open(fp, "wb") as file:
file.write(r.read())

except weberror.HTTPError as e:
if e.code == 404:
raise ValueError("The system is unable to find the requested action (the conversion isn't found)")
elif e.code == 422:
raise ValueError('Input file appears to be corrupted')
except ValueError as e:
except ValueError:
raise ValueError("The url isn't available yet")

def delete(self, id: str):
def delete(self, id: str) -> None:
"""Deletes or cancels a conversion"""
r = request.Request(
url='https://api.convertio.co/convert/' + id,
method='DELETE',
)
try:
r = request.urlopen(r)
data = json.loads(r.read().decode('utf8'))
# data = json.loads(r.read().decode('utf8'))
except weberror.HTTPError as e:
if e.code == 404:
raise ValueError("File not found")
Expand All @@ -182,21 +193,21 @@ def cancel(self, id: str):
"""Cancels a conversion"""
self.delete(id)

def conversions_list(self, status='all', count=1):
def conversions_list(self, status: str = 'all', count: int = 1) -> Any:
"""Gets the list of the client's conversions (count=-1 for all the conversions)."""
data = {
'apikey': self.token,
'status': status,
'count': count
}

r = request.Request(url=f'https://api.convertio.co/convert/list',
r = request.Request(url='https://api.convertio.co/convert/list',
method='POST',
data=json.dumps(data).encode('utf8'))
try:
r = request.urlopen(r)
data = json.loads(r.read().decode('utf8'))
return data['data']
result = json.loads(r.read().decode('utf8'))
return result['data']
except weberror.HTTPError as e:
if e.code == 400:
raise ValueError('Incorrect status value')
Expand Down
19 changes: 12 additions & 7 deletions conversion.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
from typing import Optional

from convertio.types import ConversionStatusResult


class Conversion:
def __init__(self, data) -> None:
def __init__(self, data: ConversionStatusResult) -> None:
self.code = data['code']
self.status = data['status']
self.id = data['data']['id']
self.step = data['data']['step']
self.step_percent = data['data']['step_percent']
self.minutes = data['data']['minutes']
try:
self.output_url = data['data']['output']['url']
self.output_size = data['data']['output']['size']
except:
self.output_url = "Url not available yet"
self.output_url: str = data['data']['output']['url']
self.output_size: Optional[int] = data['data']['output']['size']
except Exception:
self.output_url: str = "Url not available yet"
self.output_size = None

def __repr__(self):
return f'<Response [{self.code}]> {self.status} | {self.step} - {self.step_percent} % \n {self.output_url}'
return f'<Response [{self.code}]> {self.status} | {self.step} - {self.step_percent} % \n {self.output_url}'
9 changes: 6 additions & 3 deletions options.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
def lang_code(language):
from typing import Optional


def lang_code(language: str) -> str:
lang_codes = {
'afrikaans': 'afr',
'albanian': 'sqi',
Expand Down Expand Up @@ -89,8 +92,8 @@ def __init__(self, language: str):


class Options:
def __init__(self, langs: list, page_nums: str = None) -> None:
self.langs = []
def __init__(self, langs: list[Lang], page_nums: Optional[str] = None) -> None:
self.langs: list[str] = []
for lang in langs:
self.langs.append(lang.code)
self.page_nums = page_nums
51 changes: 51 additions & 0 deletions types.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from typing import Any, Optional, TypedDict


class ConversionPostResult(TypedDict):
code: int
status: str
data: 'ConversionPostResultDictData'


class ConversionPostResultDictData(TypedDict):
id: str
minutes: str


class ConversionPostDict(TypedDict, total=False):
apikey: str
input: str
file: str
filename: Optional[str]
outputformat: str
options: Optional['ConversionPostDictOptions']


class ConversionPostDictOptions(TypedDict):
ocr_enabled: bool
ocr_settings: 'ConversionPostDictOptionsOcrSettings'


class ConversionPostDictOptionsOcrSettings(TypedDict, total=False):
langs: list[str]
page_nums: Optional[str]


class ConversionStatusResult(TypedDict):
code: int
status: str
data: 'ConversionStatusResultData'


class ConversionStatusResultData(TypedDict):
id: str
step: str
step_percent: int
minutes: int
output: 'ConversionStatusResultDataOutPut'


class ConversionStatusResultDataOutPut(TypedDict):
url: str
size: int
files: dict[Any, Any]

0 comments on commit ced4cd3

Please sign in to comment.