File size: 10,875 Bytes
d3f5d5b
 
 
 
 
 
 
 
f015cb7
d3f5d5b
 
 
 
 
 
 
f015cb7
d3f5d5b
 
 
 
 
f015cb7
d3f5d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f015cb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
eb69a42
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
"""Read-only client for Re:port Flow's public template gallery.

This module must never call authenticated APIs (duplicate, PDF generate,
OAuth). The Hugging Face Space is an anonymous showcase.
"""

from __future__ import annotations

import io
import json
from typing import Any
from urllib.parse import urljoin

import httpx

GALLERY_API_BASE = "https://re-port-flow.com/api/v1/public/templates"
PUBLIC_THUMB_BASE = "https://re-port-flow.com/api/v1/public/assets/templates"
REGISTER_URL = "https://re-port-flow.com/register"
MCP_URL = "https://mcp.re-port-flow.com/mcp"
PAGE_LIMIT = 100
MAX_SCAN = 300
REQUEST_TIMEOUT_S = 15.0
MAX_THUMB_BYTES = 8_000_000

# Paths that would write to a workspace or mint credentials. A test asserts
# none of these strings appear as request URLs in this module.
FORBIDDEN_URL_FRAGMENTS = (
    "/duplicate",
    "generate_pdf",
    "/oauth/",
    "/token",
)


class GalleryError(Exception):
    """User-visible failure talking to the public gallery API."""


def _client() -> httpx.Client:
    return httpx.Client(
        timeout=REQUEST_TIMEOUT_S,
        headers={"Accept": "application/json"},
        follow_redirects=True,
    )


def _get_json(client: httpx.Client, url: str, params: dict[str, Any] | None = None) -> Any:
    if any(fragment in url for fragment in FORBIDDEN_URL_FRAGMENTS):
        raise GalleryError("Refusing to call a non-public gallery URL.")
    try:
        response = client.get(url, params=params)
        response.raise_for_status()
    except httpx.TimeoutException as err:
        raise GalleryError("The public gallery timed out. Try again in a moment.") from err
    except httpx.HTTPStatusError as err:
        status = err.response.status_code
        raise GalleryError(f"Public gallery returned HTTP {status}.") from err
    except httpx.RequestError as err:
        raise GalleryError("Could not reach the public gallery.") from err
    content_type = err_content_type(response)
    if "json" not in content_type:
        # Production CDN has been observed to turn API 404 into HTML 200.
        raise GalleryError("Public gallery did not return JSON.")
    try:
        return response.json()
    except json.JSONDecodeError as err:
        raise GalleryError("Public gallery returned invalid JSON.") from err


def err_content_type(response: httpx.Response) -> str:
    return (response.headers.get("content-type") or "").lower()


def list_categories(client: httpx.Client | None = None) -> list[dict[str, Any]]:
    own = client is None
    http = client or _client()
    try:
        payload = _get_json(http, f"{GALLERY_API_BASE}/categories")
    finally:
        if own:
            http.close()
    categories = payload.get("categories") if isinstance(payload, dict) else None
    if not isinstance(categories, list):
        raise GalleryError("Public gallery category list was malformed.")
    return [c for c in categories if isinstance(c, dict) and isinstance(c.get("code"), str)]


def _matches(item: dict[str, Any], query: str) -> bool:
    needle = query.strip().casefold()
    if not needle:
        return True
    haystacks: list[str] = []
    for key in ("title", "description", "category", "slug"):
        value = item.get(key)
        if isinstance(value, str):
            haystacks.append(value)
    tags = item.get("tags")
    if isinstance(tags, list):
        haystacks.extend(t for t in tags if isinstance(t, str))
    return any(needle in text.casefold() for text in haystacks)


def search_templates(
    query: str = "",
    category: str | None = None,
    sort: str = "popular",
    limit: int = 20,
    client: httpx.Client | None = None,
) -> dict[str, Any]:
    """List public templates, optionally filtered by keyword on the client.

    The public list API has no text search parameter (category / cursor /
    limit / sort only), so this scans pages and filters locally.
    """
    if sort not in ("newest", "popular"):
        sort = "popular"
    limit = max(1, min(limit, 50))
    own = client is None
    http = client or _client()
    scanned: list[dict[str, Any]] = []
    cursor: str | None = None
    truncated = False
    try:
        while len(scanned) < MAX_SCAN:
            params: dict[str, Any] = {"limit": PAGE_LIMIT, "sort": sort}
            if category:
                params["category"] = category
            if cursor:
                params["cursor"] = cursor
            payload = _get_json(http, GALLERY_API_BASE, params=params)
            if not isinstance(payload, dict):
                raise GalleryError("Public gallery list was malformed.")
            items = payload.get("items")
            if not isinstance(items, list):
                raise GalleryError("Public gallery list was malformed.")
            page = [i for i in items if isinstance(i, dict)]
            scanned.extend(page)
            cursor = payload.get("nextCursor")
            if not page or not isinstance(cursor, str) or not cursor:
                break
        else:
            truncated = True
    finally:
        if own:
            http.close()

    matched = [item for item in scanned if _matches(item, query)]
    shown = matched[:limit]
    return {
        "items": shown,
        "matched": len(matched),
        "scanned": len(scanned),
        "truncated": truncated,
        "registerUrl": REGISTER_URL,
        "mcpUrl": MCP_URL,
    }


def get_template(slug: str, client: httpx.Client | None = None) -> dict[str, Any]:
    cleaned = slug.strip()
    if not cleaned:
        raise GalleryError("Enter a template slug from the search results.")
    if "/" in cleaned or ".." in cleaned:
        raise GalleryError("That slug is not valid.")
    url = urljoin(f"{GALLERY_API_BASE}/", cleaned)
    if not url.startswith(f"{GALLERY_API_BASE}/"):
        raise GalleryError("That slug is not valid.")
    own = client is None
    http = client or _client()
    try:
        payload = _get_json(http, url)
    finally:
        if own:
            http.close()
    if not isinstance(payload, dict) or not isinstance(payload.get("slug"), str):
        raise GalleryError("Public gallery detail was malformed.")
    payload["registerUrl"] = REGISTER_URL
    payload["mcpUrl"] = MCP_URL
    return payload


def public_thumbnail_url(slug: str) -> str:
    cleaned = slug.strip()
    if not cleaned or "/" in cleaned or ".." in cleaned:
        raise GalleryError("That slug is not valid.")
    url = f"{PUBLIC_THUMB_BASE}/{cleaned}/thumbnail"
    if not url.startswith(f"{PUBLIC_THUMB_BASE}/"):
        raise GalleryError("That slug is not valid.")
    return url


def _pdf_first_page_png(data: bytes) -> bytes:
    import pypdfium2 as pdfium
    from PIL import Image  # pypdfium2.to_pil requires Pillow to be importable

    document = pdfium.PdfDocument(data)
    try:
        page = document[0]
        bitmap = page.render(scale=1.6)
        image = bitmap.to_pil()
        if image.mode != "RGB":
            image = image.convert("RGB")
    finally:
        document.close()
    buffer = io.BytesIO()
    image.save(buffer, format="PNG")
    return buffer.getvalue()


def fetch_thumbnail_png(slug: str, client: httpx.Client | None = None) -> bytes:
    """GET the public thumbnail and return a PNG.

    The official URL is a PDF (thumbnail.pdf). Chrome blocks that PDF when
    iframed from a Hugging Face Space, so this Space rasterizes page 1.
    """
    url = public_thumbnail_url(slug)
    if any(fragment in url for fragment in FORBIDDEN_URL_FRAGMENTS):
        raise GalleryError("Refusing to call a non-public gallery URL.")
    own = client is None
    http = client or _client()
    try:
        try:
            response = http.get(url, headers={"Accept": "application/pdf,image/*,*/*"})
            response.raise_for_status()
        except httpx.TimeoutException as err:
            raise GalleryError("The public thumbnail timed out.") from err
        except httpx.HTTPStatusError as err:
            raise GalleryError(
                f"Public thumbnail returned HTTP {err.response.status_code}."
            ) from err
        except httpx.RequestError as err:
            raise GalleryError("Could not reach the public thumbnail.") from err
        if len(response.content) > MAX_THUMB_BYTES:
            raise GalleryError("Public thumbnail was too large.")
        content_type = (response.headers.get("content-type") or "").lower()
        body = response.content
    finally:
        if own:
            http.close()
    if content_type.startswith("image/"):
        return body
    if "pdf" in content_type or body.startswith(b"%PDF"):
        try:
            return _pdf_first_page_png(body)
        except Exception as err:
            raise GalleryError("Could not render the public thumbnail PDF.") from err
    raise GalleryError("Public thumbnail was not an image or PDF.")


def mcp_search(
    query: str = "",
    category: str | None = None,
    sort: str = "popular",
    client: httpx.Client | None = None,
) -> dict[str, Any]:
    """JSON body for the Hub MCP search tool. Read-only public list."""
    payload = search_templates(query=query, category=category, sort=sort, client=client)
    items = []
    for item in payload.get("items") or []:
        if not isinstance(item, dict):
            continue
        items.append(
            {
                "slug": item.get("slug"),
                "title": item.get("title"),
                "category": item.get("category"),
                "description": item.get("description"),
            }
        )
    return {
        "items": items,
        "matched": payload.get("matched", len(items)),
        "scanned": payload.get("scanned", 0),
        "truncated": bool(payload.get("truncated")),
        "registerUrl": REGISTER_URL,
        "mcpUrl": MCP_URL,
        "note": (
            "These slugs cannot render a document from this Space. "
            f"Sign up at {REGISTER_URL} and connect {MCP_URL}."
        ),
    }


def mcp_template(slug: str, client: httpx.Client | None = None) -> dict[str, Any]:
    """JSON body for the Hub MCP detail tool. Read-only public detail."""
    item = get_template(slug, client=client)
    return {
        "slug": item.get("slug"),
        "title": item.get("title"),
        "category": item.get("category"),
        "version": item.get("version"),
        "description": item.get("description"),
        "registerUrl": REGISTER_URL,
        "mcpUrl": MCP_URL,
        "note": (
            "To fill and render this template, sign up at "
            f"{REGISTER_URL} then use {MCP_URL}."
        ),
    }


def mcp_register() -> dict[str, str]:
    return {
        "registerUrl": REGISTER_URL,
        "mcpUrl": MCP_URL,
        "note": (
            "Create a free account, then connect the product MCP. "
            "Do not send workspace credentials to this Space."
        ),
    }