perchance-chat-api 0.1.1__py3-none-any.whl

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.
@@ -0,0 +1,3 @@
1
+ """Unofficial Perchance AI character chat API."""
2
+
3
+ __version__ = "0.1.1"
@@ -0,0 +1,76 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Optional
5
+
6
+ from playwright.async_api import Browser, BrowserContext, Playwright, async_playwright
7
+
8
+ from .config import Settings
9
+
10
+
11
+ @dataclass
12
+ class BrowserSession:
13
+ """A Playwright session that either owns Chrome or attaches to your Chrome."""
14
+
15
+ playwright: Playwright
16
+ browser: Browser
17
+ context: BrowserContext
18
+ owns_browser: bool
19
+ owns_context: bool
20
+
21
+ async def close(self) -> None:
22
+ # Pages are closed by the caller. We only tear down resources we created.
23
+ if self.owns_context:
24
+ await self.context.close()
25
+ if self.owns_browser:
26
+ await self.browser.close()
27
+ await self.playwright.stop()
28
+
29
+
30
+ async def open_browser_session(settings: Settings) -> BrowserSession:
31
+ """Open a Chrome context using either CDP attachment or a fresh launch.
32
+
33
+ When ``ACC_CHROME_CDP_URL`` is set, Playwright connects to an already-running
34
+ Chrome and uses its first context. A new tab is created there, so it shares
35
+ that browser's localStorage (including Perchance's ``userKey``) and cookies.
36
+ """
37
+ playwright = await async_playwright().start()
38
+ try:
39
+ if settings.chrome_cdp_url:
40
+ browser = await playwright.chromium.connect_over_cdp(settings.chrome_cdp_url)
41
+ owns_browser = False
42
+ contexts = browser.contexts
43
+ if contexts:
44
+ context = contexts[0]
45
+ owns_context = False
46
+ else:
47
+ context = await browser.new_context(
48
+ viewport={"width": 1280, "height": 800},
49
+ )
50
+ owns_context = True
51
+ else:
52
+ args = ["--disable-blink-features=AutomationControlled"]
53
+ if settings.browser_offscreen:
54
+ args += ["--window-position=-32000,-32000", "--window-size=800,600"]
55
+ launch: dict[str, Any] = {
56
+ "headless": settings.headless,
57
+ "args": args,
58
+ }
59
+ if settings.chrome_channel:
60
+ launch["channel"] = settings.chrome_channel
61
+ browser = await playwright.chromium.launch(**launch)
62
+ owns_browser = True
63
+ context = await browser.new_context(
64
+ viewport={"width": 1280, "height": 800},
65
+ )
66
+ owns_context = True
67
+ return BrowserSession(
68
+ playwright=playwright,
69
+ browser=browser,
70
+ context=context,
71
+ owns_browser=owns_browser,
72
+ owns_context=owns_context,
73
+ )
74
+ except Exception:
75
+ await playwright.stop()
76
+ raise
@@ -0,0 +1,13 @@
1
+ from __future__ import annotations
2
+
3
+ import uvicorn
4
+
5
+ from .config import settings
6
+
7
+
8
+ def main() -> None:
9
+ uvicorn.run("perchance_chat_api.main:app", host=settings.host, port=settings.port)
10
+
11
+
12
+ if __name__ == "__main__":
13
+ main()
@@ -0,0 +1,41 @@
1
+ from __future__ import annotations
2
+
3
+ from pathlib import Path
4
+ from typing import Literal
5
+
6
+ from pydantic_settings import BaseSettings, SettingsConfigDict
7
+
8
+
9
+ class Settings(BaseSettings):
10
+ """Runtime configuration. Every field can be overridden with an ACC_* env var."""
11
+
12
+ model_config = SettingsConfigDict(env_prefix="ACC_", env_file=".env", extra="ignore")
13
+
14
+ host: str = "127.0.0.1"
15
+ port: int = 8000
16
+ db_path: str = "./data/perchance-chat.db"
17
+ data_dir: str = "./data"
18
+ api_key: str = ""
19
+
20
+ headless: bool = False
21
+ browser_offscreen: bool = False
22
+ chrome_channel: str = "chrome"
23
+ chrome_cdp_url: str = ""
24
+ verify_timeout_seconds: int = 60
25
+ generate_timeout_seconds: int = 180
26
+
27
+ image_provider: Literal["perchance", "http"] = "perchance"
28
+ image_api_url: str = ""
29
+ image_api_key: str = ""
30
+ image_timeout_seconds: int = 150
31
+
32
+ @property
33
+ def db_file(self) -> Path:
34
+ return Path(self.db_path).expanduser().resolve()
35
+
36
+ @property
37
+ def data_path(self) -> Path:
38
+ return Path(self.data_dir).expanduser().resolve()
39
+
40
+
41
+ settings = Settings()
@@ -0,0 +1,130 @@
1
+ from __future__ import annotations
2
+
3
+ import sqlite3
4
+ from pathlib import Path
5
+ from typing import Any, Iterable, Optional, Sequence
6
+
7
+ import aiosqlite
8
+
9
+
10
+ SCHEMA = """
11
+ PRAGMA journal_mode = WAL;
12
+ PRAGMA foreign_keys = ON;
13
+
14
+ CREATE TABLE IF NOT EXISTS characters (
15
+ id TEXT PRIMARY KEY,
16
+ name TEXT NOT NULL,
17
+ description TEXT NOT NULL DEFAULT '',
18
+ instruction TEXT NOT NULL DEFAULT '',
19
+ reminder TEXT NOT NULL DEFAULT '',
20
+ greeting TEXT NOT NULL DEFAULT '',
21
+ strict_rules TEXT NOT NULL DEFAULT '[]',
22
+ created_at TEXT NOT NULL,
23
+ updated_at TEXT NOT NULL
24
+ );
25
+
26
+ CREATE TABLE IF NOT EXISTS lorebook (
27
+ id TEXT PRIMARY KEY,
28
+ character_id TEXT NOT NULL REFERENCES characters(id) ON DELETE CASCADE,
29
+ keys TEXT NOT NULL DEFAULT '[]',
30
+ content TEXT NOT NULL DEFAULT '',
31
+ comment TEXT NOT NULL DEFAULT '',
32
+ position TEXT NOT NULL DEFAULT 'before',
33
+ priority INTEGER NOT NULL DEFAULT 0,
34
+ enabled INTEGER NOT NULL DEFAULT 1
35
+ );
36
+
37
+ CREATE INDEX IF NOT EXISTS idx_lorebook_character ON lorebook(character_id);
38
+
39
+ CREATE TABLE IF NOT EXISTS chats (
40
+ id TEXT PRIMARY KEY,
41
+ title TEXT NOT NULL DEFAULT '',
42
+ character_ids TEXT NOT NULL DEFAULT '[]',
43
+ user_name TEXT NOT NULL DEFAULT 'Anon',
44
+ memory TEXT NOT NULL DEFAULT '',
45
+ settings TEXT NOT NULL DEFAULT '{}',
46
+ created_at TEXT NOT NULL,
47
+ updated_at TEXT NOT NULL
48
+ );
49
+
50
+ CREATE TABLE IF NOT EXISTS messages (
51
+ id TEXT PRIMARY KEY,
52
+ chat_id TEXT NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
53
+ seq INTEGER NOT NULL,
54
+ role TEXT NOT NULL,
55
+ speaker TEXT NOT NULL DEFAULT '',
56
+ content TEXT NOT NULL DEFAULT '',
57
+ image_id TEXT,
58
+ created_at TEXT NOT NULL
59
+ );
60
+
61
+ CREATE INDEX IF NOT EXISTS idx_messages_chat_seq ON messages(chat_id, seq);
62
+
63
+ CREATE TABLE IF NOT EXISTS images (
64
+ id TEXT PRIMARY KEY,
65
+ chat_id TEXT,
66
+ prompt TEXT NOT NULL,
67
+ negative_prompt TEXT NOT NULL DEFAULT '',
68
+ shape TEXT NOT NULL DEFAULT 'square',
69
+ resolution TEXT NOT NULL DEFAULT '768x768',
70
+ seed INTEGER NOT NULL DEFAULT -1,
71
+ file_extension TEXT NOT NULL DEFAULT 'png',
72
+ width INTEGER NOT NULL DEFAULT 0,
73
+ height INTEGER NOT NULL DEFAULT 0,
74
+ data_url TEXT,
75
+ provider TEXT NOT NULL DEFAULT '',
76
+ created_at TEXT NOT NULL
77
+ );
78
+ """
79
+
80
+
81
+ class Database:
82
+ """Thin async SQLite wrapper. All values are bound parameters."""
83
+
84
+ def __init__(self, path: Path) -> None:
85
+ self.path = path
86
+ self.conn: Optional[aiosqlite.Connection] = None
87
+
88
+ async def connect(self) -> None:
89
+ self.path.parent.mkdir(parents=True, exist_ok=True)
90
+ self.conn = await aiosqlite.connect(str(self.path))
91
+ self.conn.row_factory = sqlite3.Row
92
+ await self.conn.executescript(SCHEMA)
93
+ await self.conn.commit()
94
+
95
+ async def close(self) -> None:
96
+ if self.conn is not None:
97
+ await self.conn.close()
98
+ self.conn = None
99
+
100
+ async def __aenter__(self) -> "Database":
101
+ await self.connect()
102
+ return self
103
+
104
+ async def __aexit__(self, *_: Any) -> None:
105
+ await self.close()
106
+
107
+ def _require(self) -> aiosqlite.Connection:
108
+ if self.conn is None:
109
+ raise RuntimeError("Database is not connected")
110
+ return self.conn
111
+
112
+ async def execute(self, sql: str, params: Sequence[Any] = ()) -> None:
113
+ await self._require().execute(sql, tuple(params))
114
+ await self._require().commit()
115
+
116
+ async def executemany(self, sql: str, rows: Iterable[Sequence[Any]]) -> None:
117
+ await self._require().executemany(sql, [tuple(r) for r in rows])
118
+ await self._require().commit()
119
+
120
+ async def fetchone(self, sql: str, params: Sequence[Any] = ()) -> Optional[dict]:
121
+ cur = await self._require().execute(sql, tuple(params))
122
+ row = await cur.fetchone()
123
+ await cur.close()
124
+ return dict(row) if row is not None else None
125
+
126
+ async def fetchall(self, sql: str, params: Sequence[Any] = ()) -> list[dict]:
127
+ cur = await self._require().execute(sql, tuple(params))
128
+ rows = await cur.fetchall()
129
+ await cur.close()
130
+ return [dict(r) for r in rows]
@@ -0,0 +1,220 @@
1
+ from __future__ import annotations
2
+
3
+ import asyncio
4
+ import base64
5
+ from dataclasses import dataclass
6
+ from typing import Optional
7
+
8
+ import httpx
9
+ from playwright.async_api import Page
10
+
11
+ from .browser import BrowserSession, open_browser_session
12
+ from .config import Settings
13
+ from .perchance import PerchanceError
14
+
15
+ RESOLUTIONS = {
16
+ "square": "768x768",
17
+ "portrait": "512x768",
18
+ "landscape": "768x512",
19
+ }
20
+
21
+
22
+ @dataclass
23
+ class GeneratedImage:
24
+ data_url: str
25
+ file_extension: str
26
+ width: int
27
+ height: int
28
+ provider: str
29
+
30
+
31
+ class ImageProvider:
32
+ async def generate(
33
+ self,
34
+ prompt: str,
35
+ negative_prompt: str = "",
36
+ shape: str = "square",
37
+ seed: int = -1,
38
+ guidance_scale: float = 7.0,
39
+ style: str = "",
40
+ ) -> GeneratedImage:
41
+ raise NotImplementedError
42
+
43
+ async def close(self) -> None:
44
+ return None
45
+
46
+
47
+ class HTTPImageProvider(ImageProvider):
48
+ """Works with any JSON image endpoint (local SD WebUI, OpenRouter, etc.)."""
49
+
50
+ def __init__(self, settings: Settings) -> None:
51
+ if not settings.image_api_url:
52
+ raise PerchanceError("ACC_IMAGE_API_URL must be set for the http image provider")
53
+ self.url = settings.image_api_url
54
+ self.key = settings.image_api_key
55
+ self.timeout = settings.image_timeout_seconds
56
+
57
+ async def generate(
58
+ self, prompt: str, negative_prompt: str = "", shape: str = "square",
59
+ seed: int = -1, guidance_scale: float = 7.0, style: str = "",
60
+ ) -> GeneratedImage:
61
+ headers = {"Content-Type": "application/json"}
62
+ if self.key:
63
+ headers["Authorization"] = f"Bearer {self.key}"
64
+ payload = {
65
+ "prompt": prompt,
66
+ "negative_prompt": negative_prompt,
67
+ "shape": shape,
68
+ "resolution": RESOLUTIONS.get(shape, "768x768"),
69
+ "seed": seed,
70
+ "guidance_scale": guidance_scale,
71
+ "style": style,
72
+ }
73
+ async with httpx.AsyncClient(timeout=self.timeout, headers=headers) as client:
74
+ response = await client.post(self.url, json=payload)
75
+ response.raise_for_status()
76
+ data = response.json()
77
+ data_url = data.get("data_url") or data.get("image")
78
+ url = data.get("url")
79
+ if not data_url and url:
80
+ async with httpx.AsyncClient(timeout=self.timeout) as client:
81
+ image_response = await client.get(url)
82
+ image_response.raise_for_status()
83
+ mime = image_response.headers.get("content-type", "image/png").split(";")[0]
84
+ encoded = base64.b64encode(image_response.content).decode("ascii")
85
+ data_url = f"data:{mime};base64,{encoded}"
86
+ if not data_url:
87
+ raise PerchanceError("image endpoint returned no image data")
88
+ if not data_url.startswith("data:"):
89
+ data_url = f"data:image/png;base64,{data_url}"
90
+ ext = data.get("file_extension", "png").lstrip(".")
91
+ if "jpeg" in data_url[:40] or "jpg" in data_url[:40]:
92
+ ext = "jpg"
93
+ return GeneratedImage(data_url, ext, int(data.get("width") or 0), int(data.get("height") or 0), "http")
94
+
95
+
96
+ class PerchanceImageProvider(ImageProvider):
97
+ """Best-effort browser automation of perchance.org/ai-text-to-image-generator.
98
+
99
+ Perchance gates image generation behind an ad-access code and a one-time
100
+ setup step. When that setup cannot complete, a clear PerchanceError is raised
101
+ and you can switch to ACC_IMAGE_PROVIDER=http with your own endpoint.
102
+ """
103
+
104
+ PAGE_URL = "https://perchance.org/ai-text-to-image-generator"
105
+
106
+ def __init__(self, settings: Settings) -> None:
107
+ self.settings = settings
108
+ self._session: Optional[BrowserSession] = None
109
+ self._page: Optional[Page] = None
110
+ self._lock = asyncio.Lock()
111
+
112
+ async def _start(self) -> None:
113
+ if self._page is not None:
114
+ return
115
+ self._session = await open_browser_session(self.settings)
116
+ self._page = await self._session.context.new_page()
117
+ await self._page.goto(self.PAGE_URL, wait_until="domcontentloaded", timeout=60_000)
118
+ await self._page.wait_for_timeout(4_000)
119
+
120
+ async def close(self) -> None:
121
+ if self._page is not None:
122
+ try:
123
+ await self._page.close()
124
+ except Exception:
125
+ pass
126
+ if self._session is not None:
127
+ await self._session.close()
128
+ self._session = None
129
+ self._page = None
130
+
131
+ async def generate(
132
+ self, prompt: str, negative_prompt: str = "", shape: str = "square",
133
+ seed: int = -1, guidance_scale: float = 7.0, style: str = "",
134
+ ) -> GeneratedImage:
135
+ async with self._lock:
136
+ await self._start()
137
+ page = self._page
138
+ assert page is not None
139
+ gen_frame = None
140
+ for frame in page.frames:
141
+ try:
142
+ if await frame.locator("#generateButtonEl").count():
143
+ gen_frame = frame
144
+ break
145
+ except Exception:
146
+ pass
147
+ if gen_frame is None:
148
+ raise PerchanceError("could not find Perchance image generator controls")
149
+
150
+ textareas = gen_frame.locator("textarea")
151
+ if await textareas.count() == 0:
152
+ raise PerchanceError("could not find Perchance prompt box")
153
+ full_prompt = prompt
154
+ if negative_prompt:
155
+ full_prompt += f" (negative::: {negative_prompt})"
156
+ if seed >= 0:
157
+ full_prompt += f" (seed:::{seed})"
158
+ if style:
159
+ full_prompt += f" (style:::{style})"
160
+ await textareas.last.fill(full_prompt)
161
+ await gen_frame.locator("#generateButtonEl").click()
162
+
163
+ image_frame = None
164
+ for _ in range(30):
165
+ await page.wait_for_timeout(1000)
166
+ matches = [f for f in page.frames if "image-generation.perchance.org/embed" in f.url]
167
+ if matches:
168
+ image_frame = matches[0]
169
+ break
170
+ if image_frame is None:
171
+ raise PerchanceError("Perchance did not start image generation")
172
+
173
+ deadline = asyncio.get_event_loop().time() + self.settings.image_timeout_seconds
174
+ status = ""
175
+ while asyncio.get_event_loop().time() < deadline:
176
+ info = await image_frame.evaluate(
177
+ """() => {
178
+ const img = [...document.querySelectorAll('img')].find(e => e.src && e.src.length > 100);
179
+ return {
180
+ src: img ? img.src : '',
181
+ width: img ? img.naturalWidth : 0,
182
+ height: img ? img.naturalHeight : 0,
183
+ status: (document.body.innerText || '').slice(0, 200)
184
+ };
185
+ }"""
186
+ )
187
+ status = info.get("status", "")
188
+ if info.get("width", 0) > 0 and info.get("src"):
189
+ src = info["src"]
190
+ if src.startswith("blob:"):
191
+ src = await image_frame.evaluate(
192
+ "async (u) => { const b = await (await fetch(u)).blob(); "
193
+ "return await new Promise(r => { const f = new FileReader(); "
194
+ "f.onload = () => r(f.result); f.readAsDataURL(b); }); }",
195
+ src,
196
+ )
197
+ if not src.startswith("data:"):
198
+ data = await image_frame.evaluate(
199
+ "async (u) => { const r = await fetch(u); const b = await r.blob(); "
200
+ "return await new Promise(res => { const f = new FileReader(); "
201
+ "f.onload = () => res(f.result); f.readAsDataURL(b); }); }",
202
+ src,
203
+ )
204
+ src = data
205
+ ext = "jpg" if "jpeg" in src[:40] or "jpg" in src[:40] else "png"
206
+ return GeneratedImage(
207
+ src, ext, int(info["width"]), int(info["height"]), "perchance"
208
+ )
209
+ await page.wait_for_timeout(1500)
210
+ raise PerchanceError(
211
+ "Perchance image generation did not finish (last status: "
212
+ f"{status!r}). Their ad-access/one-time setup may be required; "
213
+ "use ACC_IMAGE_PROVIDER=http with your own endpoint instead."
214
+ )
215
+
216
+
217
+ def make_image_provider(settings: Settings) -> ImageProvider:
218
+ if settings.image_provider == "http":
219
+ return HTTPImageProvider(settings)
220
+ return PerchanceImageProvider(settings)