GiantPandas commited on
Commit
949155e
·
verified ·
1 Parent(s): 354ff33

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +21 -17
app.py CHANGED
@@ -354,23 +354,27 @@ def embed_file(file, scale: float):
354
  # ---------- 1. PDF ----------
355
  if ext == ".pdf":
356
  # 输出 JS:把 Base64 转 Blob,然后注入/更新 iframe
 
357
  return f"""
358
- <script>
359
- const bytes = Uint8Array.from(atob("{data}"), c => c.charCodeAt(0));
360
- const blob = new Blob([bytes], {{ type: "application/pdf" }});
361
- const url = URL.createObjectURL(blob);
362
-
363
- let iframe = document.getElementById("pdf_view");
364
- if (!iframe) {{
365
- iframe = document.createElement("iframe");
366
- iframe.id = "pdf_view";
367
- iframe.style = "width:100%;height:800px;border:none;";
368
- document.currentScript.parentElement.appendChild(iframe);
369
- }}
370
- iframe.src = url + "#zoom={int(scale*100)}";
371
- </script>
372
- """
373
- # ---------- 2. 图片 ----------
 
 
 
374
  else:
375
  return (
376
  f'<div style="overflow:auto;border:1px solid #ccc;'
@@ -403,7 +407,7 @@ if __name__ == '__main__':
403
  pdf_show = PDF(label='Preview', interactive=False, visible=True, height=800)
404
 
405
  slider = gr.Slider(0.5, 3.0, value=1.0, step=0.1, label="缩放倍数")
406
- out = gr.HTML(sanitize=False)
407
 
408
  file.change(embed_file, [file, slider], out)
409
  slider.change(embed_file, [file, slider], out)
 
354
  # ---------- 1. PDF ----------
355
  if ext == ".pdf":
356
  # 输出 JS:把 Base64 转 Blob,然后注入/更新 iframe
357
+ pdf_b64 = base64.b64encode(pathlib.Path(file.name).read_bytes()).decode()
358
  return f"""
359
+ <script>
360
+ // -------- base64 转为二进制 Blob ----------
361
+ const bytes = Uint8Array.from(
362
+ atob("{pdf_b64}"), ch => ch.charCodeAt(0)
363
+ );
364
+ const blobUrl = URL.createObjectURL(
365
+ new Blob([bytes], {{type: "application/pdf"}})
366
+ );
367
+ // -------- 创建或更新 iframe ----------
368
+ let frame = document.getElementById("pdf_view");
369
+ if (!frame) {{
370
+ frame = document.createElement("iframe");
371
+ frame.id = "pdf_view";
372
+ frame.style = "width:100%;height:800px;border:none;";
373
+ document.currentScript.parentElement.appendChild(frame);
374
+ }}
375
+ frame.src = blobUrl + "#zoom={int(scale*100)}";
376
+ </script>
377
+ """
378
  else:
379
  return (
380
  f'<div style="overflow:auto;border:1px solid #ccc;'
 
407
  pdf_show = PDF(label='Preview', interactive=False, visible=True, height=800)
408
 
409
  slider = gr.Slider(0.5, 3.0, value=1.0, step=0.1, label="缩放倍数")
410
+ out = gr.HTML()
411
 
412
  file.change(embed_file, [file, slider], out)
413
  slider.change(embed_file, [file, slider], out)