paintqr 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- paintqr-0.1.0/.gitignore +5 -0
- paintqr-0.1.0/LICENSE +21 -0
- paintqr-0.1.0/PKG-INFO +96 -0
- paintqr-0.1.0/README.md +80 -0
- paintqr-0.1.0/pyproject.toml +28 -0
- paintqr-0.1.0/src/paintqr/__init__.py +213 -0
- paintqr-0.1.0/src/paintqr/__main__.py +86 -0
paintqr-0.1.0/.gitignore
ADDED
paintqr-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 PaintQR
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
paintqr-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: paintqr
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: QR codes whose own squares draw your logo, photo or word: a client of the PaintQR API
|
|
5
|
+
Project-URL: Homepage, https://paintqr.com/
|
|
6
|
+
Project-URL: Documentation, https://paintqr.com/developers/
|
|
7
|
+
Author: PaintQR
|
|
8
|
+
License-Expression: MIT
|
|
9
|
+
License-File: LICENSE
|
|
10
|
+
Keywords: generator,logo,qr,qr code,qrcode
|
|
11
|
+
Classifier: Operating System :: OS Independent
|
|
12
|
+
Classifier: Programming Language :: Python :: 3
|
|
13
|
+
Classifier: Topic :: Multimedia :: Graphics
|
|
14
|
+
Requires-Python: >=3.9
|
|
15
|
+
Description-Content-Type: text/markdown
|
|
16
|
+
|
|
17
|
+
# PaintQR for Python
|
|
18
|
+
|
|
19
|
+
QR codes whose own squares draw your logo, photo or word. This is the Python client and command-line tool for the
|
|
20
|
+
[PaintQR API](https://paintqr.com/developers/). It needs nothing but Python 3.9 or later.
|
|
21
|
+
|
|
22
|
+
pip install paintqr
|
|
23
|
+
|
|
24
|
+
Make an API key in the API tab of your [dashboard](https://paintqr.com/account/) and put it in the environment:
|
|
25
|
+
|
|
26
|
+
export PAINTQR_API_KEY=pqr_...
|
|
27
|
+
|
|
28
|
+
## In Python
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from paintqr import Client
|
|
32
|
+
|
|
33
|
+
pq = Client()
|
|
34
|
+
code = pq.make(url="https://example.com/menu", letters="MENU")
|
|
35
|
+
pq.save(code, "menu.png")
|
|
36
|
+
print(code["scan"]["verdict"], code["min_print_cm"])
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
A logo, an icon, or no picture at all:
|
|
40
|
+
|
|
41
|
+
```python
|
|
42
|
+
pq.make(url="https://example.com", logo="logo.png", preset="colour")
|
|
43
|
+
pq.make(url="https://example.com", icon="phosphor:coffee", preset="accent", accent="#7a3b12")
|
|
44
|
+
pq.make(text="Table 7", plain=True)
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
Check a design before making it. A check costs nothing and counts nothing:
|
|
48
|
+
|
|
49
|
+
```python
|
|
50
|
+
verdict = pq.check(url="https://example.com/menu", logo="logo.png")
|
|
51
|
+
if verdict["scan"]["verdict"] == "ok":
|
|
52
|
+
code = pq.make(url="https://example.com/menu", logo="logo.png")
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
or let `make` do it: `pq.make(..., check_first=True)` refuses to make a code that phones cannot read.
|
|
56
|
+
|
|
57
|
+
### Editable links (with a plan)
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
code = pq.make(url="https://example.com/menu", logo="logo.png", editable=True)
|
|
61
|
+
print(code["short_url"]) # the address the printed code opens
|
|
62
|
+
|
|
63
|
+
link = code["short_url"].rsplit("/", 1)[1]
|
|
64
|
+
pq.make(url="https://example.com/menu", logo="new-logo.png", editable=link) # a new picture on the same link
|
|
65
|
+
pq.change(link, destination="https://example.com/autumn-menu") # send the printed code elsewhere
|
|
66
|
+
print(pq.stats(link, days=30)["scans"])
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
### When something is refused
|
|
70
|
+
|
|
71
|
+
```python
|
|
72
|
+
from paintqr import PaintQRError
|
|
73
|
+
|
|
74
|
+
try:
|
|
75
|
+
pq.make(url="https://example.com", logo="logo.png", detail="low")
|
|
76
|
+
except PaintQRError as e:
|
|
77
|
+
print(e.status, e.message) # the message says what to change
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
A busy service (503) or a request to slow down (429) is waited out and tried again, three times by default:
|
|
81
|
+
`Client(retries=5)`.
|
|
82
|
+
|
|
83
|
+
## On the command line
|
|
84
|
+
|
|
85
|
+
paintqr make --url https://example.com/menu --letters MENU -o menu.png
|
|
86
|
+
paintqr make --url https://example.com --logo logo.png --preset colour -o code.pdf --size-cm 6
|
|
87
|
+
paintqr make --url https://example.com/menu --logo new-logo.png --onto SX8VNE
|
|
88
|
+
paintqr check --url https://example.com --icon phosphor:coffee
|
|
89
|
+
paintqr icons coffee
|
|
90
|
+
paintqr links
|
|
91
|
+
paintqr usage
|
|
92
|
+
|
|
93
|
+
`make` asks for the verdict first and says what it is, with the smallest size to print at. It ends with status 0 for
|
|
94
|
+
a code that scans well, 2 for one with little margin, 1 when nothing was made.
|
|
95
|
+
|
|
96
|
+
Every field of a request and of an answer is described at https://paintqr.com/developers/ .
|
paintqr-0.1.0/README.md
ADDED
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
# PaintQR for Python
|
|
2
|
+
|
|
3
|
+
QR codes whose own squares draw your logo, photo or word. This is the Python client and command-line tool for the
|
|
4
|
+
[PaintQR API](https://paintqr.com/developers/). It needs nothing but Python 3.9 or later.
|
|
5
|
+
|
|
6
|
+
pip install paintqr
|
|
7
|
+
|
|
8
|
+
Make an API key in the API tab of your [dashboard](https://paintqr.com/account/) and put it in the environment:
|
|
9
|
+
|
|
10
|
+
export PAINTQR_API_KEY=pqr_...
|
|
11
|
+
|
|
12
|
+
## In Python
|
|
13
|
+
|
|
14
|
+
```python
|
|
15
|
+
from paintqr import Client
|
|
16
|
+
|
|
17
|
+
pq = Client()
|
|
18
|
+
code = pq.make(url="https://example.com/menu", letters="MENU")
|
|
19
|
+
pq.save(code, "menu.png")
|
|
20
|
+
print(code["scan"]["verdict"], code["min_print_cm"])
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
A logo, an icon, or no picture at all:
|
|
24
|
+
|
|
25
|
+
```python
|
|
26
|
+
pq.make(url="https://example.com", logo="logo.png", preset="colour")
|
|
27
|
+
pq.make(url="https://example.com", icon="phosphor:coffee", preset="accent", accent="#7a3b12")
|
|
28
|
+
pq.make(text="Table 7", plain=True)
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Check a design before making it. A check costs nothing and counts nothing:
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
verdict = pq.check(url="https://example.com/menu", logo="logo.png")
|
|
35
|
+
if verdict["scan"]["verdict"] == "ok":
|
|
36
|
+
code = pq.make(url="https://example.com/menu", logo="logo.png")
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
or let `make` do it: `pq.make(..., check_first=True)` refuses to make a code that phones cannot read.
|
|
40
|
+
|
|
41
|
+
### Editable links (with a plan)
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
code = pq.make(url="https://example.com/menu", logo="logo.png", editable=True)
|
|
45
|
+
print(code["short_url"]) # the address the printed code opens
|
|
46
|
+
|
|
47
|
+
link = code["short_url"].rsplit("/", 1)[1]
|
|
48
|
+
pq.make(url="https://example.com/menu", logo="new-logo.png", editable=link) # a new picture on the same link
|
|
49
|
+
pq.change(link, destination="https://example.com/autumn-menu") # send the printed code elsewhere
|
|
50
|
+
print(pq.stats(link, days=30)["scans"])
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
### When something is refused
|
|
54
|
+
|
|
55
|
+
```python
|
|
56
|
+
from paintqr import PaintQRError
|
|
57
|
+
|
|
58
|
+
try:
|
|
59
|
+
pq.make(url="https://example.com", logo="logo.png", detail="low")
|
|
60
|
+
except PaintQRError as e:
|
|
61
|
+
print(e.status, e.message) # the message says what to change
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
A busy service (503) or a request to slow down (429) is waited out and tried again, three times by default:
|
|
65
|
+
`Client(retries=5)`.
|
|
66
|
+
|
|
67
|
+
## On the command line
|
|
68
|
+
|
|
69
|
+
paintqr make --url https://example.com/menu --letters MENU -o menu.png
|
|
70
|
+
paintqr make --url https://example.com --logo logo.png --preset colour -o code.pdf --size-cm 6
|
|
71
|
+
paintqr make --url https://example.com/menu --logo new-logo.png --onto SX8VNE
|
|
72
|
+
paintqr check --url https://example.com --icon phosphor:coffee
|
|
73
|
+
paintqr icons coffee
|
|
74
|
+
paintqr links
|
|
75
|
+
paintqr usage
|
|
76
|
+
|
|
77
|
+
`make` asks for the verdict first and says what it is, with the smallest size to print at. It ends with status 0 for
|
|
78
|
+
a code that scans well, 2 for one with little margin, 1 when nothing was made.
|
|
79
|
+
|
|
80
|
+
Every field of a request and of an answer is described at https://paintqr.com/developers/ .
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "paintqr"
|
|
7
|
+
dynamic = ["version"]
|
|
8
|
+
description = "QR codes whose own squares draw your logo, photo or word: a client of the PaintQR API"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.9"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
authors = [{ name = "PaintQR" }]
|
|
13
|
+
keywords = ["qr", "qr code", "qrcode", "logo", "generator"]
|
|
14
|
+
classifiers = ["Programming Language :: Python :: 3", "Operating System :: OS Independent", "Topic :: Multimedia :: Graphics"]
|
|
15
|
+
dependencies = []
|
|
16
|
+
|
|
17
|
+
[project.urls]
|
|
18
|
+
Homepage = "https://paintqr.com/"
|
|
19
|
+
Documentation = "https://paintqr.com/developers/"
|
|
20
|
+
|
|
21
|
+
[project.scripts]
|
|
22
|
+
paintqr = "paintqr.__main__:main"
|
|
23
|
+
|
|
24
|
+
[tool.hatch.version]
|
|
25
|
+
path = "src/paintqr/__init__.py"
|
|
26
|
+
|
|
27
|
+
[tool.hatch.build.targets.wheel]
|
|
28
|
+
packages = ["src/paintqr"]
|
|
@@ -0,0 +1,213 @@
|
|
|
1
|
+
"""PaintQR for Python: QR codes whose own squares draw your logo, photo or word.
|
|
2
|
+
|
|
3
|
+
from paintqr import Client
|
|
4
|
+
pq = Client() # the key is read from PAINTQR_API_KEY
|
|
5
|
+
code = pq.make(url="https://example.com/menu", letters="MENU")
|
|
6
|
+
pq.save(code, "menu.png")
|
|
7
|
+
|
|
8
|
+
A thin client of the public API documented at https://paintqr.com/developers/ . It needs nothing but Python: requests
|
|
9
|
+
are made with the standard library, named for what they are, and tried again when the service says it is busy.
|
|
10
|
+
"""
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import base64
|
|
14
|
+
import json
|
|
15
|
+
import os
|
|
16
|
+
import time
|
|
17
|
+
import urllib.error
|
|
18
|
+
import urllib.parse
|
|
19
|
+
import urllib.request
|
|
20
|
+
|
|
21
|
+
__version__ = "0.1.0"
|
|
22
|
+
__all__ = ["Client", "PaintQRError", "design", "__version__"]
|
|
23
|
+
|
|
24
|
+
BASE = "https://paintqr.com"
|
|
25
|
+
USER_AGENT = f"paintqr-python/{__version__} (+https://paintqr.com/developers/)"
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
class PaintQRError(Exception):
|
|
29
|
+
"""The service refused a request. `status` is the HTTP status, `message` what it said in plain words (what to
|
|
30
|
+
change, for a 400 or 422), `retry_after` the seconds it asked to wait, when it did."""
|
|
31
|
+
|
|
32
|
+
def __init__(self, status: int, message: str, retry_after: float | None = None):
|
|
33
|
+
super().__init__(f"{status}: {message}")
|
|
34
|
+
self.status, self.message, self.retry_after = status, message, retry_after
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
def _urllib(method: str, url: str, headers: dict, body: bytes | None, timeout: float):
|
|
38
|
+
"""One request with the standard library. Returns (status, headers, body) for every answer, refusals included."""
|
|
39
|
+
req = urllib.request.Request(url, data=body, headers=headers, method=method)
|
|
40
|
+
try:
|
|
41
|
+
with urllib.request.urlopen(req, timeout=timeout) as r:
|
|
42
|
+
return r.status, dict(r.headers.items()), r.read()
|
|
43
|
+
except urllib.error.HTTPError as e:
|
|
44
|
+
return e.code, dict(e.headers.items()), e.read()
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def design(*, url: str | None = None, text: str | None = None, vcard: dict | None = None, wifi: dict | None = None,
|
|
48
|
+
logo=None, icon: str | None = None, letters: str | None = None, plain: bool = False,
|
|
49
|
+
size: float | None = None, fit: str | None = None, background: str | None = None,
|
|
50
|
+
exact: bool | None = None, inside: bool | None = None,
|
|
51
|
+
preset: str | None = None, accent: str | None = None, palette: list | None = None,
|
|
52
|
+
detail: str | None = None, balance: str | None = None, quality: str | None = None,
|
|
53
|
+
editable: bool | str = False) -> dict:
|
|
54
|
+
"""The body of a request, from plain arguments. Exactly one kind of content (url, text, vcard, wifi) and exactly
|
|
55
|
+
one picture (logo, icon, letters, plain).
|
|
56
|
+
|
|
57
|
+
logo a path, or the bytes, of a PNG, JPEG, WebP or SVG file
|
|
58
|
+
size 1.0 fits the square between the code's corner markers; about 1.25 fills its width
|
|
59
|
+
exact keep the shapes of a logo, icon or letters exact (on unless False)
|
|
60
|
+
inside hold the picture between the corner markers, with a clear frame around it
|
|
61
|
+
editable True for a new short link; a link's code ("SX8VNE") to draw this design onto a link you already have
|
|
62
|
+
"""
|
|
63
|
+
contents = {"link": url, "text": text, "vcard": vcard, "wifi": wifi}
|
|
64
|
+
given = [k for k, v in contents.items() if v]
|
|
65
|
+
if len(given) != 1:
|
|
66
|
+
raise ValueError("give exactly one of url, text, vcard or wifi" + (f" (got {', '.join(given)})" if given else ""))
|
|
67
|
+
kind = given[0]
|
|
68
|
+
content = {"type": kind, {"link": "url"}.get(kind, kind): contents[kind]}
|
|
69
|
+
pictures = [k for k, v in (("logo", logo), ("icon", icon), ("letters", letters), ("plain", plain)) if v]
|
|
70
|
+
if len(pictures) != 1:
|
|
71
|
+
raise ValueError("give exactly one of logo, icon, letters or plain=True" + (f" (got {', '.join(pictures)})" if pictures else ""))
|
|
72
|
+
picture: dict = {}
|
|
73
|
+
if logo:
|
|
74
|
+
data = logo if isinstance(logo, (bytes, bytearray)) else open(os.fspath(logo), "rb").read()
|
|
75
|
+
picture["image"] = base64.b64encode(data).decode("ascii")
|
|
76
|
+
elif icon:
|
|
77
|
+
picture["icon"] = icon
|
|
78
|
+
elif letters:
|
|
79
|
+
picture["text"] = letters
|
|
80
|
+
else:
|
|
81
|
+
picture["plain"] = True
|
|
82
|
+
for name, value in (("zoom", size), ("fit", fit), ("background", background), ("solid", exact), ("inside", inside)):
|
|
83
|
+
if value is not None:
|
|
84
|
+
picture[name] = value
|
|
85
|
+
body: dict = {"content": content, "picture": picture}
|
|
86
|
+
style = {k: v for k, v in (("preset", preset), ("accent", accent), ("palette", palette)) if v is not None}
|
|
87
|
+
if style:
|
|
88
|
+
body["style"] = style
|
|
89
|
+
for name, value in (("detail", detail), ("balance", balance), ("quality", quality)):
|
|
90
|
+
if value is not None:
|
|
91
|
+
body[name] = value
|
|
92
|
+
if editable:
|
|
93
|
+
body["editable"] = {"code": editable} if isinstance(editable, str) else True
|
|
94
|
+
return body
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class Client:
|
|
98
|
+
"""Calls to the PaintQR API with one key.
|
|
99
|
+
|
|
100
|
+
key your API key ("pqr_..."); read from the environment variable PAINTQR_API_KEY when not given
|
|
101
|
+
retries how many times a request is tried again when the service is busy (503) or asks to slow down (429)
|
|
102
|
+
transport for tests: a function (method, url, headers, body, timeout) -> (status, headers, body)
|
|
103
|
+
"""
|
|
104
|
+
|
|
105
|
+
def __init__(self, key: str | None = None, *, base: str = BASE, timeout: float = 90, retries: int = 3,
|
|
106
|
+
user_agent: str = USER_AGENT, transport=None):
|
|
107
|
+
self.key = key or os.environ.get("PAINTQR_API_KEY") or ""
|
|
108
|
+
if not self.key:
|
|
109
|
+
raise ValueError("no API key: pass key=..., or set PAINTQR_API_KEY. Keys are made in the API tab of https://paintqr.com/account/")
|
|
110
|
+
self.base, self.timeout, self.retries, self.user_agent = base.rstrip("/"), timeout, retries, user_agent
|
|
111
|
+
self._send = transport or _urllib
|
|
112
|
+
self._sleep = time.sleep
|
|
113
|
+
|
|
114
|
+
# ---- the request itself
|
|
115
|
+
def _call(self, method: str, path: str, body: dict | None = None, query: dict | None = None, raw: bool = False):
|
|
116
|
+
url = self.base + path
|
|
117
|
+
if query:
|
|
118
|
+
q = {k: v for k, v in query.items() if v is not None}
|
|
119
|
+
if q:
|
|
120
|
+
url += "?" + urllib.parse.urlencode(q)
|
|
121
|
+
headers = {"Authorization": f"Bearer {self.key}", "User-Agent": self.user_agent, "Accept": "application/json"}
|
|
122
|
+
data = None
|
|
123
|
+
if body is not None:
|
|
124
|
+
data = json.dumps(body).encode("utf-8")
|
|
125
|
+
headers["Content-Type"] = "application/json"
|
|
126
|
+
for attempt in range(self.retries + 1):
|
|
127
|
+
status, answered, content = self._send(method, url, headers, data, self.timeout)
|
|
128
|
+
wait = _seconds({k.lower(): v for k, v in answered.items()}.get("retry-after"))
|
|
129
|
+
if status in (429, 503) and attempt < self.retries:
|
|
130
|
+
self._sleep(min(60.0, wait if wait is not None else 2.0 * (attempt + 1)))
|
|
131
|
+
continue
|
|
132
|
+
if status >= 400:
|
|
133
|
+
raise PaintQRError(status, _message(content), wait)
|
|
134
|
+
return content if raw else (json.loads(content) if content else None)
|
|
135
|
+
|
|
136
|
+
# ---- codes
|
|
137
|
+
def check(self, body: dict | None = None, **arguments) -> dict:
|
|
138
|
+
"""Whether a design would scan and how small it can print, without making it: nothing is counted."""
|
|
139
|
+
return self._call("POST", "/v1/check", body or design(**arguments))
|
|
140
|
+
|
|
141
|
+
def make(self, body: dict | None = None, *, check_first: bool = False, **arguments) -> dict:
|
|
142
|
+
"""Make a code. Returns the service's answer: its `id`, the scan verdict, the smallest print size, what the
|
|
143
|
+
code carries (`encoded`), any `notes`, and `short_url` when it is editable.
|
|
144
|
+
|
|
145
|
+
check_first ask for the verdict first and refuse to make a code that phones cannot read (PaintQRError 422)
|
|
146
|
+
"""
|
|
147
|
+
body = body or design(**arguments)
|
|
148
|
+
if check_first:
|
|
149
|
+
verdict = self.check(body)["scan"]
|
|
150
|
+
if verdict["verdict"] == "fail":
|
|
151
|
+
raise PaintQRError(422, "phones cannot read this design: " + "; ".join(verdict.get("reasons") or []))
|
|
152
|
+
return self._call("POST", "/v1/codes", body)
|
|
153
|
+
|
|
154
|
+
def get(self, code_id: str) -> dict:
|
|
155
|
+
return self._call("GET", f"/v1/codes/{_id(code_id)}")
|
|
156
|
+
|
|
157
|
+
def image(self, code, *, format: str = "png", size: int | None = None, size_cm: float | None = None, dpi: int | None = None) -> bytes:
|
|
158
|
+
"""The code's file: PNG (size in pixels, or size_cm with dpi), SVG or PDF. SVG and PDF need a plan."""
|
|
159
|
+
return self._call("GET", f"/v1/codes/{_id(code)}/image", query=dict(format=format, size=size, size_cm=size_cm, dpi=dpi), raw=True)
|
|
160
|
+
|
|
161
|
+
def save(self, code, path, **how) -> str:
|
|
162
|
+
"""Write the code's file; the format follows the file name (.png, .svg, .pdf) unless given."""
|
|
163
|
+
path = os.fspath(path)
|
|
164
|
+
how.setdefault("format", {"svg": "svg", "pdf": "pdf"}.get(path.rsplit(".", 1)[-1].lower(), "png"))
|
|
165
|
+
data = self.image(code, **how)
|
|
166
|
+
with open(path, "wb") as f:
|
|
167
|
+
f.write(data)
|
|
168
|
+
return path
|
|
169
|
+
|
|
170
|
+
def usage(self) -> dict:
|
|
171
|
+
return self._call("GET", "/v1/usage")
|
|
172
|
+
|
|
173
|
+
def icons(self, query: str = "", *, limit: int = 60) -> list:
|
|
174
|
+
"""Ready-made icons whose name matches; pass an icon's `id` as icon=... to make a code with it."""
|
|
175
|
+
return self._call("GET", "/v1/icons", query=dict(q=query, limit=limit))["icons"]
|
|
176
|
+
|
|
177
|
+
# ---- editable links
|
|
178
|
+
def links(self, *, label: str | None = None) -> list:
|
|
179
|
+
return self._call("GET", "/v1/links", query=dict(label=label))["links"]
|
|
180
|
+
|
|
181
|
+
def link(self, code: str) -> dict:
|
|
182
|
+
return self._call("GET", f"/v1/links/{code}")
|
|
183
|
+
|
|
184
|
+
def stats(self, code: str | None = None, *, days: int | None = None, start: str | None = None, end: str | None = None) -> dict:
|
|
185
|
+
"""Scans of one link, or of every link when no code is given, over the last `days` or between two dates."""
|
|
186
|
+
return self._call("GET", f"/v1/links/{code}/stats" if code else "/v1/stats", query={"days": days, "from": start, "to": end})
|
|
187
|
+
|
|
188
|
+
def change(self, code: str, *, destination: str | None = None, active: bool | None = None, name: str | None = None,
|
|
189
|
+
labels: list | None = None) -> dict:
|
|
190
|
+
"""Send a link somewhere else, pause or resume it, rename it or set its labels."""
|
|
191
|
+
body = {k: v for k, v in dict(destination=destination, active=active, name=name, labels=labels).items() if v is not None}
|
|
192
|
+
return self._call("PATCH", f"/v1/links/{code}", body)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _id(code) -> str:
|
|
196
|
+
return code["id"] if isinstance(code, dict) else str(code)
|
|
197
|
+
|
|
198
|
+
|
|
199
|
+
def _seconds(value) -> float | None:
|
|
200
|
+
try:
|
|
201
|
+
return float(value)
|
|
202
|
+
except (TypeError, ValueError):
|
|
203
|
+
return None
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def _message(content: bytes) -> str:
|
|
207
|
+
"""What the service said, from its JSON; for an answer that is not ours (a proxy's page), a short plain line."""
|
|
208
|
+
try:
|
|
209
|
+
detail = json.loads(content).get("detail")
|
|
210
|
+
return detail if isinstance(detail, str) else json.dumps(detail)
|
|
211
|
+
except Exception:
|
|
212
|
+
text = content[:200].decode("utf-8", "replace").strip()
|
|
213
|
+
return "the request did not reach the API" + (f" ({text[:120]})" if text and "<" not in text else "")
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
"""The command line: `paintqr make --url https://example.com/menu --letters MENU -o menu.png`."""
|
|
2
|
+
from __future__ import annotations
|
|
3
|
+
|
|
4
|
+
import argparse
|
|
5
|
+
import json
|
|
6
|
+
import sys
|
|
7
|
+
|
|
8
|
+
from . import Client, PaintQRError, __version__, design
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
def _design_arguments(p: argparse.ArgumentParser) -> None:
|
|
12
|
+
c = p.add_argument_group("what the code carries (one of)")
|
|
13
|
+
c.add_argument("--url"); c.add_argument("--text")
|
|
14
|
+
c.add_argument("--wifi", metavar="NAME", help="network name; with --wifi-password")
|
|
15
|
+
c.add_argument("--wifi-password", default="")
|
|
16
|
+
g = p.add_argument_group("the picture (one of)")
|
|
17
|
+
g.add_argument("--logo", metavar="FILE", help="PNG, JPEG, WebP or SVG")
|
|
18
|
+
g.add_argument("--icon", metavar="ID", help="from `paintqr icons WORD`")
|
|
19
|
+
g.add_argument("--letters"); g.add_argument("--plain", action="store_true", help="a code without a picture")
|
|
20
|
+
s = p.add_argument_group("how it looks")
|
|
21
|
+
s.add_argument("--preset", choices=["classic", "colour", "accent", "cutout", "halftone", "poster"])
|
|
22
|
+
s.add_argument("--accent", metavar="#RRGGBB"); s.add_argument("--size", type=float, help="1.0 fits between the corner markers")
|
|
23
|
+
s.add_argument("--inside", action="store_true", default=None, help="keep the picture between the corner markers")
|
|
24
|
+
s.add_argument("--loose", action="store_true", help="do not keep the picture's shapes exact")
|
|
25
|
+
s.add_argument("--detail", choices=["auto", "low", "medium", "high", "max"])
|
|
26
|
+
s.add_argument("--balance", choices=["safe", "balanced", "picture"]); s.add_argument("--quality", choices=["standard", "best"])
|
|
27
|
+
e = p.add_argument_group("editable links (need a plan)")
|
|
28
|
+
e.add_argument("--editable", action="store_true", help="a new short link you can send elsewhere later")
|
|
29
|
+
e.add_argument("--onto", metavar="CODE", help="draw this design onto a link you already have")
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _body(a) -> dict:
|
|
33
|
+
wifi = {"ssid": a.wifi, "password": a.wifi_password, "auth": "WPA" if a.wifi_password else "nopass"} if a.wifi else None
|
|
34
|
+
return design(url=a.url, text=a.text, wifi=wifi, logo=a.logo, icon=a.icon, letters=a.letters, plain=a.plain,
|
|
35
|
+
size=a.size, inside=a.inside, exact=False if a.loose else None, preset=a.preset, accent=a.accent,
|
|
36
|
+
detail=a.detail, balance=a.balance, quality=a.quality, editable=a.onto or a.editable)
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def main(argv=None) -> int:
|
|
40
|
+
p = argparse.ArgumentParser(prog="paintqr", description="QR codes whose own squares draw your logo, photo or word. "
|
|
41
|
+
"The key is read from PAINTQR_API_KEY.")
|
|
42
|
+
p.add_argument("--version", action="version", version=__version__)
|
|
43
|
+
p.add_argument("--key", help="your API key, in place of PAINTQR_API_KEY")
|
|
44
|
+
sub = p.add_subparsers(dest="command", required=True)
|
|
45
|
+
m = sub.add_parser("make", help="make a code and save its file")
|
|
46
|
+
_design_arguments(m)
|
|
47
|
+
m.add_argument("-o", "--output", default="code.png", help="file to write: .png, .svg or .pdf (default code.png)")
|
|
48
|
+
m.add_argument("--size-cm", type=float, help="printed width of the file"); m.add_argument("--pixels", type=int)
|
|
49
|
+
m.add_argument("--no-check", action="store_true", help="make the code without asking for the verdict first")
|
|
50
|
+
c = sub.add_parser("check", help="whether a design would scan, without making it")
|
|
51
|
+
_design_arguments(c)
|
|
52
|
+
i = sub.add_parser("icons", help="find a ready-made icon"); i.add_argument("word")
|
|
53
|
+
sub.add_parser("links", help="your editable links"); sub.add_parser("usage", help="codes made this month")
|
|
54
|
+
a = p.parse_args(argv)
|
|
55
|
+
try:
|
|
56
|
+
pq = Client(a.key)
|
|
57
|
+
if a.command == "make":
|
|
58
|
+
code = pq.make(_body(a), check_first=not a.no_check)
|
|
59
|
+
how = {k: v for k, v in (("size_cm", a.size_cm), ("size", a.pixels)) if v}
|
|
60
|
+
path = pq.save(code, a.output, **how)
|
|
61
|
+
scan = code["scan"]
|
|
62
|
+
print(f"{path}: {scan['verdict']}, print at {code['min_print_cm']} cm or larger" + (f", {code['short_url']}" if code.get("short_url") else ""))
|
|
63
|
+
for line in list(scan.get("reasons") or []) + [n["message"] for n in code.get("notes") or []]:
|
|
64
|
+
print(" " + line)
|
|
65
|
+
return 0 if scan["verdict"] == "ok" else 2
|
|
66
|
+
if a.command == "check":
|
|
67
|
+
out = pq.check(_body(a))
|
|
68
|
+
print(json.dumps(out, indent=2, ensure_ascii=False))
|
|
69
|
+
return 0 if out["scan"]["verdict"] == "ok" else 2
|
|
70
|
+
if a.command == "icons":
|
|
71
|
+
for icon in pq.icons(a.word):
|
|
72
|
+
print(f"{icon['id']:40s} {icon['name']}")
|
|
73
|
+
return 0
|
|
74
|
+
if a.command == "links":
|
|
75
|
+
for link in pq.links():
|
|
76
|
+
print(f"{link['short_url']:28s} {'paused ' if not link.get('active', True) else ''}{link.get('destination') or ''}")
|
|
77
|
+
return 0
|
|
78
|
+
print(json.dumps(pq.usage(), indent=2))
|
|
79
|
+
return 0
|
|
80
|
+
except (PaintQRError, ValueError, OSError) as e:
|
|
81
|
+
print(f"paintqr: {e}", file=sys.stderr)
|
|
82
|
+
return 1
|
|
83
|
+
|
|
84
|
+
|
|
85
|
+
if __name__ == "__main__":
|
|
86
|
+
sys.exit(main())
|