shinapi 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.
Potentially problematic release.
This version of shinapi might be problematic. Click here for more details.
- shinapi-0.1.0/.gitignore +23 -0
- shinapi-0.1.0/LICENSE +21 -0
- shinapi-0.1.0/PKG-INFO +32 -0
- shinapi-0.1.0/README.md +20 -0
- shinapi-0.1.0/package.json +20 -0
- shinapi-0.1.0/pyproject.toml +19 -0
- shinapi-0.1.0/shinapi/__init__.py +212 -0
- shinapi-0.1.0/shinapi/py.typed +0 -0
- shinapi-0.1.0/src/python.test.ts +53 -0
- shinapi-0.1.0/src/venv.ts +90 -0
- shinapi-0.1.0/tests/test_client.py +116 -0
- shinapi-0.1.0/tsconfig.json +7 -0
shinapi-0.1.0/.gitignore
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
node_modules/
|
|
2
|
+
dist/
|
|
3
|
+
dist-worker/
|
|
4
|
+
.astro/
|
|
5
|
+
.turbo/
|
|
6
|
+
.wrangler/
|
|
7
|
+
.dev.vars
|
|
8
|
+
*.local
|
|
9
|
+
.env
|
|
10
|
+
.DS_Store
|
|
11
|
+
coverage/
|
|
12
|
+
*.tsbuildinfo
|
|
13
|
+
tmp-*
|
|
14
|
+
scratch/
|
|
15
|
+
|
|
16
|
+
# Generated by wrangler types in each Worker on install and before its typecheck: the runtime at its compatibility date and flags.
|
|
17
|
+
apps/*/worker-configuration.d.ts
|
|
18
|
+
__pycache__/
|
|
19
|
+
|
|
20
|
+
# Written by scripts/deploy.ts beside each wrangler.json while it deploys.
|
|
21
|
+
apps/*/wrangler.deploy.json
|
|
22
|
+
.venv/
|
|
23
|
+
.api-key
|
shinapi-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ShinAPI
|
|
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.
|
shinapi-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: shinapi
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Search what high-authority Japanese sites say now. The Python client of ShinAPI.
|
|
5
|
+
Project-URL: Homepage, https://shinapi.com
|
|
6
|
+
Project-URL: Documentation, https://docs.shinapi.com
|
|
7
|
+
License-Expression: MIT
|
|
8
|
+
License-File: LICENSE
|
|
9
|
+
Keywords: agents,japan,japanese,llm,rag,search
|
|
10
|
+
Requires-Python: >=3.10
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
|
|
13
|
+
# shinapi
|
|
14
|
+
|
|
15
|
+
Search what high-authority Japanese sites say now. The Python client of [ShinAPI](https://shinapi.com).
|
|
16
|
+
|
|
17
|
+
```sh
|
|
18
|
+
pip install shinapi
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
```python
|
|
22
|
+
from shinapi import ShinAPI
|
|
23
|
+
|
|
24
|
+
shinapi = ShinAPI()
|
|
25
|
+
answer = shinapi.search("2026年の年収の壁はいくらですか")
|
|
26
|
+
|
|
27
|
+
if answer["outcome"] == "answered":
|
|
28
|
+
for passage in answer["results"]:
|
|
29
|
+
print(passage["url"], passage["text"])
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Get a key in the [console](https://console.shinapi.com), and read the [docs](https://docs.shinapi.com).
|
shinapi-0.1.0/README.md
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
# shinapi
|
|
2
|
+
|
|
3
|
+
Search what high-authority Japanese sites say now. The Python client of [ShinAPI](https://shinapi.com).
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
pip install shinapi
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
```python
|
|
10
|
+
from shinapi import ShinAPI
|
|
11
|
+
|
|
12
|
+
shinapi = ShinAPI()
|
|
13
|
+
answer = shinapi.search("2026年の年収の壁はいくらですか")
|
|
14
|
+
|
|
15
|
+
if answer["outcome"] == "answered":
|
|
16
|
+
for passage in answer["results"]:
|
|
17
|
+
print(passage["url"], passage["text"])
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
Get a key in the [console](https://console.shinapi.com), and read the [docs](https://docs.shinapi.com).
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@shinapi/sdk-python",
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"private": true,
|
|
5
|
+
"description": "The Python client of ShinAPI, tested here against the contract and published to PyPI from its pyproject.toml",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"exports": {
|
|
8
|
+
"./venv": "./src/venv.ts"
|
|
9
|
+
},
|
|
10
|
+
"scripts": {
|
|
11
|
+
"typecheck": "tsc --noEmit",
|
|
12
|
+
"test": "vitest run"
|
|
13
|
+
},
|
|
14
|
+
"devDependencies": {
|
|
15
|
+
"@shinapi/contract": "workspace:*",
|
|
16
|
+
"@types/node": "catalog:",
|
|
17
|
+
"typescript": "catalog:",
|
|
18
|
+
"vitest": "catalog:"
|
|
19
|
+
}
|
|
20
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "shinapi"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Search what high-authority Japanese sites say now. The Python client of ShinAPI."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
license = "MIT"
|
|
11
|
+
requires-python = ">=3.10"
|
|
12
|
+
keywords = ["search", "japan", "japanese", "llm", "rag", "agents"]
|
|
13
|
+
|
|
14
|
+
[project.urls]
|
|
15
|
+
Homepage = "https://shinapi.com"
|
|
16
|
+
Documentation = "https://docs.shinapi.com"
|
|
17
|
+
|
|
18
|
+
[tool.hatch.build.targets.wheel]
|
|
19
|
+
packages = ["shinapi"]
|
|
@@ -0,0 +1,212 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import os
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable, Literal, Optional, Sequence, TypedDict
|
|
7
|
+
from urllib.error import HTTPError
|
|
8
|
+
from urllib.request import Request, urlopen
|
|
9
|
+
|
|
10
|
+
__all__ = [
|
|
11
|
+
"SEARCH_DESCRIPTION",
|
|
12
|
+
"SEARCH_INPUT",
|
|
13
|
+
"ErrorCode",
|
|
14
|
+
"Licence",
|
|
15
|
+
"Outcome",
|
|
16
|
+
"SearchResponse",
|
|
17
|
+
"SearchResult",
|
|
18
|
+
"ShinAPI",
|
|
19
|
+
"ShinAPIError",
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
Outcome = Literal["answered", "no_match_in_scope", "out_of_scope"]
|
|
23
|
+
|
|
24
|
+
Licence = Literal["pdl-1.0", "gjstu-2.0", "cc-by-4.0", "cc0-1.0", "publisher-terms"]
|
|
25
|
+
|
|
26
|
+
ErrorCode = Literal[
|
|
27
|
+
"invalid_request",
|
|
28
|
+
"unauthorized",
|
|
29
|
+
"payment_required",
|
|
30
|
+
"forbidden",
|
|
31
|
+
"rate_limited",
|
|
32
|
+
"not_found",
|
|
33
|
+
"internal",
|
|
34
|
+
"unavailable",
|
|
35
|
+
]
|
|
36
|
+
|
|
37
|
+
SEARCH_DESCRIPTION = " ".join(
|
|
38
|
+
[
|
|
39
|
+
"Search what high-authority Japanese sites say now, and get the passages as published, with the publisher, the URL,",
|
|
40
|
+
"the dates and the credit line to show. Only pages written in Japanese are indexed, so ask in Japanese, translating",
|
|
41
|
+
"a question asked in another language first.",
|
|
42
|
+
"The outcome is answered, no_match_in_scope (the index holds the words but no passage answers) or out_of_scope (the",
|
|
43
|
+
"index holds nothing on it, so ask a general search instead). When incomplete is true, ask again before concluding.",
|
|
44
|
+
]
|
|
45
|
+
)
|
|
46
|
+
|
|
47
|
+
SEARCH_INPUT: dict[str, Any] = {
|
|
48
|
+
"$schema": "https://json-schema.org/draft/2020-12/schema",
|
|
49
|
+
"type": "object",
|
|
50
|
+
"properties": {
|
|
51
|
+
"query": {
|
|
52
|
+
"type": "string",
|
|
53
|
+
"minLength": 1,
|
|
54
|
+
"maxLength": 512,
|
|
55
|
+
"description": "The question or keywords, in Japanese.",
|
|
56
|
+
},
|
|
57
|
+
"max_results": {
|
|
58
|
+
"default": 8,
|
|
59
|
+
"description": "The most passages to return.",
|
|
60
|
+
"type": "integer",
|
|
61
|
+
"minimum": 1,
|
|
62
|
+
"maximum": 32,
|
|
63
|
+
},
|
|
64
|
+
"exclude_domains": {
|
|
65
|
+
"default": [],
|
|
66
|
+
"description": "Sites to leave out, each a host such as example.co.jp: "
|
|
67
|
+
"no passage of that host or of a host under it is returned.",
|
|
68
|
+
"maxItems": 64,
|
|
69
|
+
"type": "array",
|
|
70
|
+
"items": {
|
|
71
|
+
"type": "string",
|
|
72
|
+
"minLength": 1,
|
|
73
|
+
"maxLength": 256,
|
|
74
|
+
"pattern": "^[^/?#@:\\s]+$",
|
|
75
|
+
},
|
|
76
|
+
},
|
|
77
|
+
"exclude_text": {
|
|
78
|
+
"default": [],
|
|
79
|
+
"description": "Phrases to leave out: no passage whose title or text holds one is returned, "
|
|
80
|
+
"whatever its width or case.",
|
|
81
|
+
"maxItems": 8,
|
|
82
|
+
"type": "array",
|
|
83
|
+
"items": {"type": "string", "minLength": 1, "maxLength": 64},
|
|
84
|
+
},
|
|
85
|
+
},
|
|
86
|
+
"required": ["query"],
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
BASE_URL = "https://api.shinapi.com"
|
|
90
|
+
TIMEOUT_S = 30.0
|
|
91
|
+
RETRIES = 2
|
|
92
|
+
WAIT_S = 0.5
|
|
93
|
+
WAIT_CEILING_S = 8.0
|
|
94
|
+
RETRIED = frozenset({429, 500, 503})
|
|
95
|
+
|
|
96
|
+
|
|
97
|
+
class SearchResult(TypedDict):
|
|
98
|
+
title: str
|
|
99
|
+
url: str
|
|
100
|
+
publisher: str
|
|
101
|
+
published_at: Optional[str]
|
|
102
|
+
author: Optional[str]
|
|
103
|
+
image: Optional[str]
|
|
104
|
+
favicon: Optional[str]
|
|
105
|
+
last_changed_at: str
|
|
106
|
+
licence: Licence
|
|
107
|
+
attribution: str
|
|
108
|
+
score: Optional[float]
|
|
109
|
+
text: str
|
|
110
|
+
|
|
111
|
+
|
|
112
|
+
class SearchResponse(TypedDict):
|
|
113
|
+
outcome: Outcome
|
|
114
|
+
incomplete: bool
|
|
115
|
+
results: list[SearchResult]
|
|
116
|
+
request_id: str
|
|
117
|
+
|
|
118
|
+
|
|
119
|
+
class ShinAPIError(Exception):
|
|
120
|
+
def __init__(
|
|
121
|
+
self, message: str, status: int, code: str, request_id: Optional[str] = None
|
|
122
|
+
) -> None:
|
|
123
|
+
super().__init__(message)
|
|
124
|
+
self.status = status
|
|
125
|
+
self.code = code
|
|
126
|
+
self.request_id = request_id
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _json_in(text: bytes) -> Any:
|
|
130
|
+
try:
|
|
131
|
+
return json.loads(text)
|
|
132
|
+
except ValueError:
|
|
133
|
+
return None
|
|
134
|
+
|
|
135
|
+
|
|
136
|
+
def _waited_for(header: Optional[str], attempt: int) -> float:
|
|
137
|
+
try:
|
|
138
|
+
asked = float(header or 0)
|
|
139
|
+
except ValueError:
|
|
140
|
+
asked = 0.0
|
|
141
|
+
waited = asked if asked > 0 else WAIT_S * 2**attempt
|
|
142
|
+
return min(waited, WAIT_CEILING_S)
|
|
143
|
+
|
|
144
|
+
|
|
145
|
+
class ShinAPI:
|
|
146
|
+
def __init__(
|
|
147
|
+
self,
|
|
148
|
+
key: Optional[str] = None,
|
|
149
|
+
*,
|
|
150
|
+
base_url: str = BASE_URL,
|
|
151
|
+
timeout: float = TIMEOUT_S,
|
|
152
|
+
retries: int = RETRIES,
|
|
153
|
+
opener: Callable[..., Any] = urlopen,
|
|
154
|
+
sleep: Callable[[float], None] = time.sleep,
|
|
155
|
+
) -> None:
|
|
156
|
+
held = key or os.environ.get("SHINAPI_KEY")
|
|
157
|
+
if not held:
|
|
158
|
+
raise ValueError("ShinAPI needs a key: pass key or set SHINAPI_KEY")
|
|
159
|
+
self._key = held
|
|
160
|
+
self._url = base_url.rstrip("/") + "/v1/search"
|
|
161
|
+
self._timeout = timeout
|
|
162
|
+
self._retries = retries
|
|
163
|
+
self._opener = opener
|
|
164
|
+
self._sleep = sleep
|
|
165
|
+
|
|
166
|
+
def search(
|
|
167
|
+
self,
|
|
168
|
+
query: str,
|
|
169
|
+
*,
|
|
170
|
+
max_results: Optional[int] = None,
|
|
171
|
+
exclude_domains: Optional[Sequence[str]] = None,
|
|
172
|
+
exclude_text: Optional[Sequence[str]] = None,
|
|
173
|
+
) -> SearchResponse:
|
|
174
|
+
asked: dict[str, Any] = {"query": query}
|
|
175
|
+
if max_results is not None:
|
|
176
|
+
asked["max_results"] = max_results
|
|
177
|
+
if exclude_domains is not None:
|
|
178
|
+
asked["exclude_domains"] = list(exclude_domains)
|
|
179
|
+
if exclude_text is not None:
|
|
180
|
+
asked["exclude_text"] = list(exclude_text)
|
|
181
|
+
attempt = 0
|
|
182
|
+
while True:
|
|
183
|
+
request = Request(
|
|
184
|
+
self._url,
|
|
185
|
+
data=json.dumps(asked).encode(),
|
|
186
|
+
headers={
|
|
187
|
+
"Authorization": f"Bearer {self._key}",
|
|
188
|
+
"Content-Type": "application/json",
|
|
189
|
+
"User-Agent": "shinapi-python",
|
|
190
|
+
},
|
|
191
|
+
method="POST",
|
|
192
|
+
)
|
|
193
|
+
try:
|
|
194
|
+
with self._opener(request, timeout=self._timeout) as response:
|
|
195
|
+
status = response.status
|
|
196
|
+
answer = _json_in(response.read())
|
|
197
|
+
except HTTPError as error:
|
|
198
|
+
if error.code not in RETRIED or attempt >= self._retries:
|
|
199
|
+
body = _json_in(error.read())
|
|
200
|
+
said = body if isinstance(body, dict) else {}
|
|
201
|
+
raise ShinAPIError(
|
|
202
|
+
said.get("error") or f"ShinAPI answered {error.code}",
|
|
203
|
+
error.code,
|
|
204
|
+
said.get("code") or "unreadable",
|
|
205
|
+
said.get("request_id"),
|
|
206
|
+
) from None
|
|
207
|
+
self._sleep(_waited_for(error.headers.get("Retry-After"), attempt))
|
|
208
|
+
attempt += 1
|
|
209
|
+
continue
|
|
210
|
+
if not isinstance(answer, dict):
|
|
211
|
+
raise ShinAPIError("ShinAPI's answer was not JSON", status, "unreadable")
|
|
212
|
+
return answer # type: ignore[return-value]
|
|
File without changes
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
2
|
+
import {
|
|
3
|
+
ERROR_CODES,
|
|
4
|
+
LICENCES,
|
|
5
|
+
OUTCOMES,
|
|
6
|
+
searchResponse,
|
|
7
|
+
searchResult,
|
|
8
|
+
searchSchemas,
|
|
9
|
+
} from "@shinapi/contract";
|
|
10
|
+
import { TOOL } from "@shinapi/contract/tool";
|
|
11
|
+
import { describe, expect, it } from "vitest";
|
|
12
|
+
|
|
13
|
+
const HERE = new URL("..", import.meta.url).pathname;
|
|
14
|
+
|
|
15
|
+
const SHAPES = `
|
|
16
|
+
import json, typing, shinapi
|
|
17
|
+
fields = lambda one: list(typing.get_type_hints(one))
|
|
18
|
+
print(json.dumps({
|
|
19
|
+
"result": fields(shinapi.SearchResult),
|
|
20
|
+
"response": fields(shinapi.SearchResponse),
|
|
21
|
+
"outcomes": typing.get_args(shinapi.Outcome),
|
|
22
|
+
"licences": typing.get_args(shinapi.Licence),
|
|
23
|
+
"errors": typing.get_args(shinapi.ErrorCode),
|
|
24
|
+
"description": shinapi.SEARCH_DESCRIPTION,
|
|
25
|
+
"input": shinapi.SEARCH_INPUT,
|
|
26
|
+
}))
|
|
27
|
+
`;
|
|
28
|
+
|
|
29
|
+
describe("the Python client", () => {
|
|
30
|
+
it("states the contract's fields and words, in its order", () => {
|
|
31
|
+
const shapes: unknown = JSON.parse(
|
|
32
|
+
execFileSync("python3", ["-c", SHAPES], { cwd: HERE, encoding: "utf8" }),
|
|
33
|
+
);
|
|
34
|
+
expect(shapes).toEqual({
|
|
35
|
+
result: Object.keys(searchResult.shape),
|
|
36
|
+
response: Object.keys(searchResponse.shape),
|
|
37
|
+
outcomes: OUTCOMES,
|
|
38
|
+
licences: LICENCES,
|
|
39
|
+
errors: ERROR_CODES,
|
|
40
|
+
description: TOOL.description,
|
|
41
|
+
input: searchSchemas().request,
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
|
|
45
|
+
it("passes its own tests", () => {
|
|
46
|
+
const run = spawnSync("python3", ["-m", "unittest", "discover", "-s", "tests"], {
|
|
47
|
+
cwd: HERE,
|
|
48
|
+
encoding: "utf8",
|
|
49
|
+
});
|
|
50
|
+
expect(run.stderr).toContain("OK");
|
|
51
|
+
expect(run.status).toBe(0);
|
|
52
|
+
});
|
|
53
|
+
});
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { execFileSync, spawnSync } from "node:child_process";
|
|
2
|
+
import { createHash } from "node:crypto";
|
|
3
|
+
import { existsSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
4
|
+
import { join, resolve } from "node:path";
|
|
5
|
+
|
|
6
|
+
const INTERPRETERS = ["python3.14", "python3.13", "python3.12", "python3.11", "python3"];
|
|
7
|
+
const RELEASE_AGE = "P7D";
|
|
8
|
+
const STAMP = "shinapi-stamp";
|
|
9
|
+
export const INSTALL_MS = 2 ** 19;
|
|
10
|
+
|
|
11
|
+
const recentEnough = (python: string): boolean =>
|
|
12
|
+
spawnSync(python, ["-c", "import sys; sys.exit(sys.version_info < (3, 11))"]).status === 0;
|
|
13
|
+
|
|
14
|
+
export function interpreter(): string {
|
|
15
|
+
const found = INTERPRETERS.find(recentEnough);
|
|
16
|
+
if (!found) throw new Error(`no Python 3.11 or later: tried ${INTERPRETERS.join(", ")}`);
|
|
17
|
+
return found;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
const projectOf = (dir: string): string => readFileSync(join(dir, "pyproject.toml"), "utf8");
|
|
21
|
+
|
|
22
|
+
const READ = [
|
|
23
|
+
"import json, sys, tomllib",
|
|
24
|
+
"project = tomllib.load(open(sys.argv[1], 'rb'))",
|
|
25
|
+
"print(json.dumps([project['project']['name'], 'build-system' in project, project['project'].get('dependencies', [])]))",
|
|
26
|
+
].join("; ");
|
|
27
|
+
|
|
28
|
+
interface Project {
|
|
29
|
+
dir: string;
|
|
30
|
+
name: string;
|
|
31
|
+
built: boolean;
|
|
32
|
+
needs: string[];
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const canonical = (name: string): string => name.toLowerCase().replace(/[-_.]+/g, "-");
|
|
36
|
+
const nameOf = (requirement: string): string =>
|
|
37
|
+
canonical(/^[A-Za-z0-9._-]+/.exec(requirement)?.[0] ?? "");
|
|
38
|
+
const texts = (value: unknown): string[] =>
|
|
39
|
+
Array.isArray(value) ? value.filter((one): one is string => typeof one === "string") : [];
|
|
40
|
+
|
|
41
|
+
function projectAt(python: string, dir: string): Project {
|
|
42
|
+
const read: unknown = JSON.parse(
|
|
43
|
+
execFileSync(python, ["-c", READ, join(dir, "pyproject.toml")], { encoding: "utf8" }),
|
|
44
|
+
);
|
|
45
|
+
const [name, built, needs] = Array.isArray(read) ? read : [];
|
|
46
|
+
return { dir, name: canonical(String(name)), built: built === true, needs: texts(needs) };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function installs(python: string, dirs: readonly string[]): string[] {
|
|
50
|
+
const projects = dirs.map((dir) => projectAt(python, dir));
|
|
51
|
+
const here = new Set(projects.filter((one) => one.built).map((one) => one.name));
|
|
52
|
+
return projects.flatMap((one) =>
|
|
53
|
+
one.built ? ["--editable", one.dir] : one.needs.filter((need) => !here.has(nameOf(need))),
|
|
54
|
+
);
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function pythonWith(dir: string, projects: readonly string[]): string {
|
|
58
|
+
const venv = join(dir, ".venv");
|
|
59
|
+
const python = join(venv, "bin", "python");
|
|
60
|
+
const base = interpreter();
|
|
61
|
+
const dirs = projects.map((one) => resolve(dir, one));
|
|
62
|
+
const version = execFileSync(base, ["--version"], { encoding: "utf8" });
|
|
63
|
+
const stamp = createHash("sha256")
|
|
64
|
+
.update([version, ...dirs.map(projectOf)].join("\0"))
|
|
65
|
+
.digest("hex");
|
|
66
|
+
const stampAt = join(venv, STAMP);
|
|
67
|
+
if (existsSync(stampAt) && readFileSync(stampAt, "utf8") === stamp) return python;
|
|
68
|
+
rmSync(venv, { recursive: true, force: true });
|
|
69
|
+
execFileSync(base, ["-m", "venv", venv]);
|
|
70
|
+
const pip = (...args: string[]) =>
|
|
71
|
+
execFileSync(python, [
|
|
72
|
+
"-m",
|
|
73
|
+
"pip",
|
|
74
|
+
"install",
|
|
75
|
+
"--quiet",
|
|
76
|
+
"--disable-pip-version-check",
|
|
77
|
+
...args,
|
|
78
|
+
]);
|
|
79
|
+
pip("pip>=26");
|
|
80
|
+
pip("--uploaded-prior-to", RELEASE_AGE, ...installs(python, dirs));
|
|
81
|
+
writeFileSync(stampAt, stamp);
|
|
82
|
+
return python;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
export function unittest(python: string, dir: string) {
|
|
86
|
+
return spawnSync(python, ["-m", "unittest", "discover", "-s", "tests"], {
|
|
87
|
+
cwd: dir,
|
|
88
|
+
encoding: "utf8",
|
|
89
|
+
});
|
|
90
|
+
}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import io
|
|
2
|
+
import json
|
|
3
|
+
import os
|
|
4
|
+
import unittest
|
|
5
|
+
from email.message import Message
|
|
6
|
+
from unittest import mock
|
|
7
|
+
from urllib.error import HTTPError
|
|
8
|
+
|
|
9
|
+
from shinapi import ShinAPI, ShinAPIError
|
|
10
|
+
|
|
11
|
+
REQUEST = "4bf92f3577b34da6a3ce929d0e0e4736"
|
|
12
|
+
ANSWER = {
|
|
13
|
+
"outcome": "out_of_scope",
|
|
14
|
+
"incomplete": False,
|
|
15
|
+
"results": [],
|
|
16
|
+
"request_id": REQUEST,
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class Response(io.BytesIO):
|
|
21
|
+
status = 200
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
def answered(body=ANSWER):
|
|
25
|
+
return Response(body if isinstance(body, bytes) else json.dumps(body).encode())
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def refused(status, code, retry_after=None):
|
|
29
|
+
headers = Message()
|
|
30
|
+
if retry_after:
|
|
31
|
+
headers["Retry-After"] = retry_after
|
|
32
|
+
body = json.dumps({"error": "why", "code": code, "request_id": REQUEST}).encode()
|
|
33
|
+
return HTTPError("https://api.example.jp", status, "", headers, io.BytesIO(body))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class Opener:
|
|
37
|
+
def __init__(self, *answers):
|
|
38
|
+
self.answers = list(answers)
|
|
39
|
+
self.asked = []
|
|
40
|
+
|
|
41
|
+
def __call__(self, request, timeout):
|
|
42
|
+
self.asked.append(request)
|
|
43
|
+
answer = self.answers.pop(0) if self.answers else answered()
|
|
44
|
+
if isinstance(answer, HTTPError):
|
|
45
|
+
raise answer
|
|
46
|
+
return answer
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def client(opener, **options):
|
|
50
|
+
slept = []
|
|
51
|
+
made = ShinAPI("shin_test", opener=opener, sleep=slept.append, **options)
|
|
52
|
+
return made, slept
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
class Search(unittest.TestCase):
|
|
56
|
+
def test_sends_the_key_the_question_and_the_count(self):
|
|
57
|
+
opener = Opener()
|
|
58
|
+
shinapi, _ = client(opener, base_url="https://api.example.jp/")
|
|
59
|
+
self.assertEqual(shinapi.search("婚姻届", max_results=4), ANSWER)
|
|
60
|
+
[request] = opener.asked
|
|
61
|
+
self.assertEqual(request.full_url, "https://api.example.jp/v1/search")
|
|
62
|
+
self.assertEqual(request.get_header("Authorization"), "Bearer shin_test")
|
|
63
|
+
self.assertEqual(json.loads(request.data), {"query": "婚姻届", "max_results": 4})
|
|
64
|
+
|
|
65
|
+
def test_sends_the_hosts_and_phrases_left_out(self):
|
|
66
|
+
opener = Opener()
|
|
67
|
+
client(opener)[0].search("婚姻届", exclude_domains=["example.jp"], exclude_text=["広告"])
|
|
68
|
+
self.assertEqual(
|
|
69
|
+
json.loads(opener.asked[0].data),
|
|
70
|
+
{"query": "婚姻届", "exclude_domains": ["example.jp"], "exclude_text": ["広告"]},
|
|
71
|
+
)
|
|
72
|
+
|
|
73
|
+
def test_leaves_the_count_out_when_none_is_given(self):
|
|
74
|
+
opener = Opener()
|
|
75
|
+
client(opener)[0].search("婚姻届")
|
|
76
|
+
self.assertEqual(json.loads(opener.asked[0].data), {"query": "婚姻届"})
|
|
77
|
+
|
|
78
|
+
def test_takes_its_key_from_the_environment_and_needs_one(self):
|
|
79
|
+
with mock.patch.dict(os.environ, {"SHINAPI_KEY": "shin_env"}):
|
|
80
|
+
opener = Opener()
|
|
81
|
+
ShinAPI(opener=opener).search("a")
|
|
82
|
+
self.assertEqual(opener.asked[0].get_header("Authorization"), "Bearer shin_env")
|
|
83
|
+
with mock.patch.dict(os.environ, {"SHINAPI_KEY": ""}):
|
|
84
|
+
with self.assertRaisesRegex(ValueError, "needs a key"):
|
|
85
|
+
ShinAPI()
|
|
86
|
+
|
|
87
|
+
def test_raises_what_the_api_said_and_asks_once(self):
|
|
88
|
+
opener = Opener(refused(402, "payment_required"))
|
|
89
|
+
with self.assertRaises(ShinAPIError) as caught:
|
|
90
|
+
client(opener)[0].search("a")
|
|
91
|
+
self.assertEqual(str(caught.exception), "why")
|
|
92
|
+
self.assertEqual((caught.exception.status, caught.exception.code), (402, "payment_required"))
|
|
93
|
+
self.assertEqual(caught.exception.request_id, REQUEST)
|
|
94
|
+
self.assertEqual(len(opener.asked), 1)
|
|
95
|
+
|
|
96
|
+
def test_asks_again_after_as_long_as_it_is_told(self):
|
|
97
|
+
opener = Opener(refused(429, "rate_limited", "1"), refused(503, "unavailable"))
|
|
98
|
+
shinapi, slept = client(opener)
|
|
99
|
+
self.assertEqual(shinapi.search("a"), ANSWER)
|
|
100
|
+
self.assertEqual(slept, [1.0, 1.0])
|
|
101
|
+
|
|
102
|
+
def test_gives_up_after_its_retries(self):
|
|
103
|
+
opener = Opener(*(refused(429, "rate_limited") for _ in range(4)))
|
|
104
|
+
shinapi, slept = client(opener)
|
|
105
|
+
with self.assertRaises(ShinAPIError):
|
|
106
|
+
shinapi.search("a")
|
|
107
|
+
self.assertEqual((len(opener.asked), slept), (3, [0.5, 1.0]))
|
|
108
|
+
|
|
109
|
+
def test_says_when_an_answer_is_not_one_it_can_read(self):
|
|
110
|
+
with self.assertRaises(ShinAPIError) as caught:
|
|
111
|
+
client(Opener(answered(b"<html>")))[0].search("a")
|
|
112
|
+
self.assertEqual(caught.exception.code, "unreadable")
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
if __name__ == "__main__":
|
|
116
|
+
unittest.main()
|