Skip to content

Commit

Permalink
Releases the Python SDK
Browse files Browse the repository at this point in the history
  • Loading branch information
Titou325 committed Mar 11, 2024
1 parent aa2ed3b commit 7e7b536
Show file tree
Hide file tree
Showing 10 changed files with 138 additions and 62 deletions.
26 changes: 26 additions & 0 deletions .github/workflows/client-py.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
name: Build and Publish

on:
push:
branches:
- main
paths:
- "packages/client-py/**"

jobs:
build-and-publish:
runs-on: ubuntu-latest
permissions:
contents: write
steps:
- uses: actions/checkout@v4
- uses: actions/setup-python@v2
with:
python-version: 3.8
# NB: we use pyproject.toml so we can straight use the build command
- run: python3 -m pip install --upgrade build twine
- run: python3 -m build
- run: python3 -m twine upload --repository pypi dist/*
env:
TWINE_USERNAME: __token__
TWINE_PASSWORD: ${{ secrets.PYPI_API }}
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,5 @@ node_modules
test
dist
.DS_Store
.env
*.pdf
2 changes: 2 additions & 0 deletions packages/client-py/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
__pycache__
**.egg-info
Empty file.
1 change: 1 addition & 0 deletions packages/client-py/onedoc/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
from .onedoc import Onedoc
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import requests
import json

from typing import Dict, Union, List, Any
from typing import Dict, Union, List, Any, BinaryIO

DEFAULT_FILE_OPTIONS = {
"cacheControl": "3600",
"contentType": "text/plain;charset=UTF-8",
"upsert": False,
}

class HtmlBuilder:
class _HtmlBuilder:
def __init__(self, title: str = None):
self.title = title or "Document"

Expand All @@ -23,10 +23,10 @@ def __init__(self, api_key: str):
self.api_key = api_key
self.endpoint = "https://app.onedoclabs.com"

def build_url(self, path: str) -> str:
def _build_url(self, path: str) -> str:
return f"{self.endpoint}{path}"

def upload_to_signed_url(self, url_to_fs: str, path: str, file_body: Any, file_options: Dict = None) -> Dict:
def _upload_to_signed_url(self, url_to_fs: str, path: str, file_body: Any, file_options: Dict = None) -> Dict:
url = f"{url_to_fs}"

options = {**DEFAULT_FILE_OPTIONS, **(file_options or {})}
Expand Down Expand Up @@ -54,10 +54,10 @@ def render(self, document: Dict) -> Dict:
save = document.get('save', False)

expires_in = document.get('expiresIn', 1)

# Initiate document rendering process
information_response = requests.post(
self.build_url("/api/docs/initiate"),
self._build_url("/api/docs/initiate"),
headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
json={"assets": assets}
)
Expand All @@ -77,16 +77,16 @@ def render(self, document: Dict) -> Dict:
asset = next((item for item in document.get('assets', []) if item['path'] == e['path']), None)

if asset and asset.get('content'):
self.upload_to_signed_url(e['signedUrl'], e['path'], asset['content'])
self._upload_to_signed_url(e['signedUrl'], e['path'], asset['content'])

elif e['path'] == "/index.html":
html_builder = HtmlBuilder(document.get('title'))
html_builder = _HtmlBuilder(document.get('title'))
style_sheets = [asset['path'] for asset in document.get('assets', []) if asset['path'].endswith(".css")]
html = html_builder.build(document['html'], style_sheets, test)
self.upload_to_signed_url(e['signedUrl'], e['path'], html)
self._upload_to_signed_url(e['signedUrl'], e['path'], html)

doc_response = requests.post(
self.build_url("/api/docs/generate"),
self._build_url("/api/docs/generate"),
headers={"x-api-key": self.api_key, "Content-Type": "application/json"},
json= json.dumps({
"uploadURL":response["uploadURL"],
Expand All @@ -100,7 +100,7 @@ def render(self, document: Dict) -> Dict:
"expiresIn": expires_in
})
)

if doc_response.status_code != 200:
return doc_response.__dict__

Expand All @@ -119,3 +119,29 @@ def render(self, document: Dict) -> Dict:
"info": {},
}

def merge(self, file_a: BinaryIO, file_a_name: str, file_b: BinaryIO, file_b_name: str):
# The server expects a single 'file' key which contains a list of all the files.
# The server will then merge the files and return the merged file.

response = requests.post(
#'http://localhost:3000/api/docs/merge',
self._build_url("/api/docs/merge"),
headers={"x-api-key": self.api_key},
files=[
("file", (file_a_name, file_a, "application/pdf")),
("file", (file_b_name, file_b, "application/pdf")),
],
)

if response.status_code != 200:
return {
"file": None,
"error": response.json().get('error', "An unknown error has occurred"),
"info": {"status": response.status_code},
}

return {
"file": response.content,
"error": None,
"info": {},
}
51 changes: 51 additions & 0 deletions packages/client-py/onedoc/test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
from onedoc import Onedoc
from dotenv import load_dotenv
from os import getenv

load_dotenv()

onedoc = Onedoc(getenv("ONEDOC_API_KEY"))

# Define your document
document = {
"html": "<h1>Table of contents</h1><a href='file://test.pdf#page=1'>First page</a><br/><a href='file://test.pdf#page=2'>Second page</a>", # Simple HTML content
"title": "My First Document",
"test": True, # Set to False to use in production
"save": False, # Set to True if you want to save the document
}

# Render the document
#result = onedoc.render(document)

#for files that are not saved, remember to use "wb" when writing file
# onedoc = Onedoc(api_key)

# # Define your document
# document = {
# "html": "<h1>Hello World</h1>", # Simple HTML content
# "title": "My First Document",
# "test": True, # Set to False to use in production
# "save": False, # Set to True if you want to save the document
# }

# # Render the document
# result = onedoc.render(document)
# print(result.get("file"))
# f = open("hellowordpierre.pdf", "wb")
# f.write(result.get("file"))
# f.close()

# Store the result to toc.pdf
#f = open("toc.pdf", "wb")
#f.write(result.get("file"))
#f.close()

firstFile = open("toc.pdf", "rb")
secondFile = open("test.pdf", "rb")

result = onedoc.merge(firstFile, "toc.pdf", secondFile, "test.pdf")

# Result is a pdf file
f = open("merged.pdf", "wb")
f.write(result.get('file'))
f.close()
19 changes: 19 additions & 0 deletions packages/client-py/pyproject.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
[project]
name = "client_onedoc"
version = "0.0.1"
authors = [
{ name="Pierre Dorge", email="[email protected]" },
{ name="Titouan Launay", email="[email protected]" },
]
description = "Onedoc SDK for Python"
readme = "README.md"
requires-python = ">=3.8"
classifiers = [
"Programming Language :: Python :: 3",
"License :: OSI Approved :: MIT License",
"Operating System :: OS Independent",
]

[project.urls]
Homepage = "https://github.com/onedoclabs/onedoc"
Issues = "https://github.com/OnedocLabs/onedoc/issues"
18 changes: 0 additions & 18 deletions packages/client-py/setup.py

This file was deleted.

33 changes: 0 additions & 33 deletions packages/client-py/tests/test_main.py

This file was deleted.

0 comments on commit 7e7b536

Please sign in to comment.