reportflow-mcp bot commited on
Commit
f015cb7
·
1 Parent(s): ebf9b42

Sync Space from reportflow-mcp@f7128e4

Browse files
Files changed (3) hide show
  1. app.py +23 -30
  2. gallery.py +71 -0
  3. requirements.txt +2 -0
app.py CHANGED
@@ -5,14 +5,16 @@ Does not generate PDFs. Sign-up and the hosted MCP server do that.
5
 
6
  from __future__ import annotations
7
 
8
- import html
9
 
10
  import gradio as gr
 
11
 
12
  from gallery import (
13
  MCP_URL,
14
  REGISTER_URL,
15
  GalleryError,
 
16
  get_template,
17
  list_categories,
18
  search_templates,
@@ -45,7 +47,7 @@ def _format_results(payload: dict) -> str:
45
  [
46
  "",
47
  "This Space does **not** generate PDFs. The first match is previewed "
48
- "below (the public thumbnail is a PDF page, not a PNG). Then "
49
  f"[sign up free]({REGISTER_URL}) and connect "
50
  f"`{MCP_URL}` to render a filled document.",
51
  ]
@@ -53,24 +55,11 @@ def _format_results(payload: dict) -> str:
53
  return "\n".join(lines)
54
 
55
 
56
- def _preview_frame(thumb_url: str | None) -> str:
57
- """Embed the public thumbnail. The API serves a PDF, not a raster image."""
58
- if not thumb_url or not thumb_url.startswith("https://"):
59
- return "<p>No public preview file for this template.</p>"
60
- safe = html.escape(thumb_url, quote=True)
61
- return (
62
- f'<p><a href="{safe}" target="_blank" rel="noopener">Open preview PDF</a></p>'
63
- f'<iframe src="{safe}" title="Template preview" '
64
- 'style="width:100%;min-height:640px;border:1px solid #444;background:#fff">'
65
- "</iframe>"
66
- )
67
-
68
-
69
  def search_gallery(
70
  query: str,
71
  category: str,
72
  sort: str,
73
- ) -> tuple[str, str, str, str]:
74
  """Search the public template gallery (unauthenticated, read-only).
75
 
76
  Args:
@@ -79,24 +68,24 @@ def search_gallery(
79
  sort: Either "popular" or "newest".
80
 
81
  Returns:
82
- Markdown table, preview iframe, first match slug, and detail markdown.
83
  """
84
  category_code = None if category in ("", "(any)") else category
85
  try:
86
  payload = search_templates(query=query or "", category=category_code, sort=sort)
87
  except GalleryError as err:
88
- return str(err), f"<p>{html.escape(str(err))}</p>", "", str(err)
89
  items = payload.get("items") or []
90
  first_slug = ""
91
  if items and isinstance(items[0].get("slug"), str):
92
  first_slug = items[0]["slug"]
93
  if first_slug:
94
- detail, frame = preview_template(first_slug)
95
- return _format_results(payload), frame, first_slug, detail
96
- return _format_results(payload), "", "", ""
97
 
98
 
99
- def preview_template(slug: str) -> tuple[str, str]:
100
  """Load one public template's details by slug (unauthenticated, read-only).
101
 
102
  Args:
@@ -104,16 +93,20 @@ def preview_template(slug: str) -> tuple[str, str]:
104
  until the user signs up and copies the template into their workspace.
105
 
106
  Returns:
107
- Markdown description and an HTML iframe of the public thumbnail PDF.
108
  """
109
  try:
110
  item = get_template(slug)
111
  except GalleryError as err:
112
- return str(err), f"<p>{html.escape(str(err))}</p>"
113
  title = item.get("title") or slug
114
  description = item.get("description") or ""
115
- thumbnail = item.get("thumbnailUrl")
116
- thumb_url = thumbnail if isinstance(thumbnail, str) and thumbnail.startswith("https://") else None
 
 
 
 
117
  body = "\n".join(
118
  [
119
  f"### {title}",
@@ -128,7 +121,7 @@ def preview_template(slug: str) -> tuple[str, str]:
128
  "This Space never calls generate or duplicate APIs.",
129
  ]
130
  )
131
- return body, _preview_frame(thumb_url)
132
 
133
 
134
  def signup_cta() -> str:
@@ -170,10 +163,10 @@ after you pick a template.
170
  search_btn = gr.Button("Search gallery", variant="primary")
171
  results = gr.Markdown()
172
  detail = gr.Markdown(label="Details")
173
- preview_frame = gr.HTML(label="Template preview (PDF)")
174
  slug = gr.Textbox(label="Template slug to preview")
175
  preview_btn = gr.Button("Preview")
176
- search_outputs = [results, preview_frame, slug, detail]
177
  search_btn.click(
178
  fn=search_gallery,
179
  inputs=[query, category, sort],
@@ -187,7 +180,7 @@ after you pick a template.
187
  preview_btn.click(
188
  fn=preview_template,
189
  inputs=[slug],
190
- outputs=[detail, preview_frame],
191
  )
192
 
193
  gr.Markdown(
 
5
 
6
  from __future__ import annotations
7
 
8
+ import io
9
 
10
  import gradio as gr
11
+ from PIL import Image
12
 
13
  from gallery import (
14
  MCP_URL,
15
  REGISTER_URL,
16
  GalleryError,
17
+ fetch_thumbnail_png,
18
  get_template,
19
  list_categories,
20
  search_templates,
 
47
  [
48
  "",
49
  "This Space does **not** generate PDFs. The first match is previewed "
50
+ "below. Then "
51
  f"[sign up free]({REGISTER_URL}) and connect "
52
  f"`{MCP_URL}` to render a filled document.",
53
  ]
 
55
  return "\n".join(lines)
56
 
57
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
  def search_gallery(
59
  query: str,
60
  category: str,
61
  sort: str,
62
+ ) -> tuple[str, str, str, Image.Image | None]:
63
  """Search the public template gallery (unauthenticated, read-only).
64
 
65
  Args:
 
68
  sort: Either "popular" or "newest".
69
 
70
  Returns:
71
+ Markdown table, first match slug, detail markdown, and a PNG preview.
72
  """
73
  category_code = None if category in ("", "(any)") else category
74
  try:
75
  payload = search_templates(query=query or "", category=category_code, sort=sort)
76
  except GalleryError as err:
77
+ return str(err), "", str(err), None
78
  items = payload.get("items") or []
79
  first_slug = ""
80
  if items and isinstance(items[0].get("slug"), str):
81
  first_slug = items[0]["slug"]
82
  if first_slug:
83
+ detail, image = preview_template(first_slug)
84
+ return _format_results(payload), first_slug, detail, image
85
+ return _format_results(payload), "", "", None
86
 
87
 
88
+ def preview_template(slug: str) -> tuple[str, Image.Image | None]:
89
  """Load one public template's details by slug (unauthenticated, read-only).
90
 
91
  Args:
 
93
  until the user signs up and copies the template into their workspace.
94
 
95
  Returns:
96
+ Markdown description and a PNG of the public thumbnail (rasterized PDF).
97
  """
98
  try:
99
  item = get_template(slug)
100
  except GalleryError as err:
101
+ return str(err), None
102
  title = item.get("title") or slug
103
  description = item.get("description") or ""
104
+ image: Image.Image | None
105
+ try:
106
+ png = fetch_thumbnail_png(str(item.get("slug") or slug))
107
+ image = Image.open(io.BytesIO(png)).convert("RGB")
108
+ except GalleryError:
109
+ image = None
110
  body = "\n".join(
111
  [
112
  f"### {title}",
 
121
  "This Space never calls generate or duplicate APIs.",
122
  ]
123
  )
124
+ return body, image
125
 
126
 
127
  def signup_cta() -> str:
 
163
  search_btn = gr.Button("Search gallery", variant="primary")
164
  results = gr.Markdown()
165
  detail = gr.Markdown(label="Details")
166
+ preview_image = gr.Image(label="Template preview", type="pil")
167
  slug = gr.Textbox(label="Template slug to preview")
168
  preview_btn = gr.Button("Preview")
169
+ search_outputs = [results, slug, detail, preview_image]
170
  search_btn.click(
171
  fn=search_gallery,
172
  inputs=[query, category, sort],
 
180
  preview_btn.click(
181
  fn=preview_template,
182
  inputs=[slug],
183
+ outputs=[detail, preview_image],
184
  )
185
 
186
  gr.Markdown(
gallery.py CHANGED
@@ -6,6 +6,7 @@ OAuth). The Hugging Face Space is an anonymous showcase.
6
 
7
  from __future__ import annotations
8
 
 
9
  import json
10
  from typing import Any
11
  from urllib.parse import urljoin
@@ -13,11 +14,13 @@ from urllib.parse import urljoin
13
  import httpx
14
 
15
  GALLERY_API_BASE = "https://re-port-flow.com/api/v1/public/templates"
 
16
  REGISTER_URL = "https://re-port-flow.com/register"
17
  MCP_URL = "https://mcp.re-port-flow.com/mcp"
18
  PAGE_LIMIT = 100
19
  MAX_SCAN = 300
20
  REQUEST_TIMEOUT_S = 15.0
 
21
 
22
  # Paths that would write to a workspace or mint credentials. A test asserts
23
  # none of these strings appear as request URLs in this module.
@@ -174,3 +177,71 @@ def get_template(slug: str, client: httpx.Client | None = None) -> dict[str, Any
174
  payload["registerUrl"] = REGISTER_URL
175
  payload["mcpUrl"] = MCP_URL
176
  return payload
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6
 
7
  from __future__ import annotations
8
 
9
+ import io
10
  import json
11
  from typing import Any
12
  from urllib.parse import urljoin
 
14
  import httpx
15
 
16
  GALLERY_API_BASE = "https://re-port-flow.com/api/v1/public/templates"
17
+ PUBLIC_THUMB_BASE = "https://re-port-flow.com/api/v1/public/assets/templates"
18
  REGISTER_URL = "https://re-port-flow.com/register"
19
  MCP_URL = "https://mcp.re-port-flow.com/mcp"
20
  PAGE_LIMIT = 100
21
  MAX_SCAN = 300
22
  REQUEST_TIMEOUT_S = 15.0
23
+ MAX_THUMB_BYTES = 8_000_000
24
 
25
  # Paths that would write to a workspace or mint credentials. A test asserts
26
  # none of these strings appear as request URLs in this module.
 
177
  payload["registerUrl"] = REGISTER_URL
178
  payload["mcpUrl"] = MCP_URL
179
  return payload
180
+
181
+
182
+ def public_thumbnail_url(slug: str) -> str:
183
+ cleaned = slug.strip()
184
+ if not cleaned or "/" in cleaned or ".." in cleaned:
185
+ raise GalleryError("That slug is not valid.")
186
+ url = f"{PUBLIC_THUMB_BASE}/{cleaned}/thumbnail"
187
+ if not url.startswith(f"{PUBLIC_THUMB_BASE}/"):
188
+ raise GalleryError("That slug is not valid.")
189
+ return url
190
+
191
+
192
+ def _pdf_first_page_png(data: bytes) -> bytes:
193
+ import pypdfium2 as pdfium
194
+ from PIL import Image # pypdfium2.to_pil requires Pillow to be importable
195
+
196
+ document = pdfium.PdfDocument(data)
197
+ try:
198
+ page = document[0]
199
+ bitmap = page.render(scale=1.6)
200
+ image = bitmap.to_pil()
201
+ if image.mode != "RGB":
202
+ image = image.convert("RGB")
203
+ finally:
204
+ document.close()
205
+ buffer = io.BytesIO()
206
+ image.save(buffer, format="PNG")
207
+ return buffer.getvalue()
208
+
209
+
210
+ def fetch_thumbnail_png(slug: str, client: httpx.Client | None = None) -> bytes:
211
+ """GET the public thumbnail and return a PNG.
212
+
213
+ The official URL is a PDF (thumbnail.pdf). Chrome blocks that PDF when
214
+ iframed from a Hugging Face Space, so this Space rasterizes page 1.
215
+ """
216
+ url = public_thumbnail_url(slug)
217
+ if any(fragment in url for fragment in FORBIDDEN_URL_FRAGMENTS):
218
+ raise GalleryError("Refusing to call a non-public gallery URL.")
219
+ own = client is None
220
+ http = client or _client()
221
+ try:
222
+ try:
223
+ response = http.get(url, headers={"Accept": "application/pdf,image/*,*/*"})
224
+ response.raise_for_status()
225
+ except httpx.TimeoutException as err:
226
+ raise GalleryError("The public thumbnail timed out.") from err
227
+ except httpx.HTTPStatusError as err:
228
+ raise GalleryError(
229
+ f"Public thumbnail returned HTTP {err.response.status_code}."
230
+ ) from err
231
+ except httpx.RequestError as err:
232
+ raise GalleryError("Could not reach the public thumbnail.") from err
233
+ if len(response.content) > MAX_THUMB_BYTES:
234
+ raise GalleryError("Public thumbnail was too large.")
235
+ content_type = (response.headers.get("content-type") or "").lower()
236
+ body = response.content
237
+ finally:
238
+ if own:
239
+ http.close()
240
+ if content_type.startswith("image/"):
241
+ return body
242
+ if "pdf" in content_type or body.startswith(b"%PDF"):
243
+ try:
244
+ return _pdf_first_page_png(body)
245
+ except Exception as err:
246
+ raise GalleryError("Could not render the public thumbnail PDF.") from err
247
+ raise GalleryError("Public thumbnail was not an image or PDF.")
requirements.txt CHANGED
@@ -1,2 +1,4 @@
1
  gradio==5.50.0
2
  httpx>=0.27.0,<1
 
 
 
1
  gradio==5.50.0
2
  httpx>=0.27.0,<1
3
+ pypdfium2>=4.30.0,<5
4
+ pillow>=10.0.0,<12