GiantPandas commited on
Commit
a2311ca
·
verified ·
1 Parent(s): f7009c5

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +108 -67
app.py CHANGED
@@ -24,6 +24,9 @@ import httpx
24
  import aiohttp
25
  import uuid
26
  import tqdm
 
 
 
27
 
28
  import requests
29
 
@@ -275,16 +278,59 @@ def to_file(image_path):
275
  return image_path
276
 
277
 
278
- # async def process_file(file_path):
279
- # if not file_path.endswith(".pdf"):
280
- # tmp_path = Path(file_path).with_suffix(".pdf")
281
- # images_to_pdf(file_path, tmp_path)
282
- # else:
283
- # tmp_path = Path(file_path)
284
 
285
- # async with httpx.AsyncClient() as client:
286
- # await send_pdf_to_parse_async(client, str(tmp_path), IP, PORT)
287
- # return str(tmp_path)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
288
 
289
 
290
  async def process_file(file_path):
@@ -307,35 +353,6 @@ async def process_file(file_path):
307
  import gradio as gr
308
  import base64, pathlib
309
 
310
- # def embed_file(file, scale):
311
- # """根据后缀决定用 PDF 还是 <img>."""
312
- # path = pathlib.Path(file.name)
313
- # data = base64.b64encode(path.read_bytes()).decode()
314
- # if path.suffix.lower() == ".pdf":
315
- # b64 = base64.b64encode(pathlib.Path(file.name).read_bytes()).decode()
316
- # # 注意:把 JS/HTML 写在一起返回给 gr.HTML
317
- # return f"""
318
- # <script>
319
- # const pdf = atob("{b64}");
320
- # const bytes = Uint8Array.from(pdf, c => c.charCodeAt(0));
321
- # const blob = new Blob([bytes], {{type: "application/pdf"}});
322
- # const url = URL.createObjectURL(blob);
323
- # const iframe = document.getElementById("pdf_view") || document.createElement("iframe");
324
- # iframe.id = "pdf_view";
325
- # iframe.style = "width:100%;height:800px;border:none";
326
- # iframe.src = url + "#zoom={int(scale*100)}";
327
- # document.currentScript.parentElement.replaceChildren(iframe);
328
- # </script>
329
- # """
330
- # else:
331
- # # 图片:CSS transform 实现 zoom;支持拖拽滚轮缩放
332
- # return (
333
- # f'<div style="overflow:auto;border:1px solid #ccc;'
334
- # f'width:100%;height:800px;text-align:center">'
335
- # f'<img src="data:image/{path.suffix[1:]};base64,{data}" '
336
- # f'style="transform:scale({scale});transform-origin:0 0;" />'
337
- # f'</div>'
338
- # )
339
 
340
 
341
  def embed_file(file, scale: float):
@@ -353,28 +370,8 @@ def embed_file(file, scale: float):
353
 
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;'
@@ -406,14 +403,58 @@ if __name__ == '__main__':
406
  clear_bu = gr.ClearButton(value='Clear')
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(sanitize_html=False)
411
-
412
- file.change(embed_file, [file, slider], out)
413
- slider.change(embed_file, [file, slider], out)
414
-
415
 
416
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
417
 
418
  example_root = os.path.join(os.path.dirname(__file__), 'examples')
419
  images = [
@@ -464,7 +505,7 @@ if __name__ == '__main__':
464
 
465
 
466
 
467
- file.change(fn=process_file, inputs=file, outputs=pdf_show)
468
 
469
 
470
  change_bu.click(
 
24
  import aiohttp
25
  import uuid
26
  import tqdm
27
+ import base64, pathlib
28
+ from io import BytesIO
29
+ from pdf2image import convert_from_bytes, convert_from_path # pip install pdf2image
30
 
31
  import requests
32
 
 
278
  return image_path
279
 
280
 
 
 
 
 
 
 
281
 
282
+
283
+ def files_to_b64(files, pdf_dpi: int = 200):
284
+ """
285
+ 把上传文件统一转成 base64 图片列表。
286
+ • 普通图片:直接 base64
287
+ • PDF :按页转成 PNG 再 base64
288
+
289
+ 返回
290
+ ----
291
+ List[str] 每个元素形如 "data:image/png;base64,xxxx..."
292
+ """
293
+ out: list[str] = []
294
+
295
+ for f in files:
296
+ # ---------- Gradio 4.x NamedString / FileData ----------
297
+ if hasattr(f, "data"): # 新版 FileData / NamedString
298
+ raw_bytes = f.data
299
+ suffix = pathlib.Path(f.name).suffix.lower()
300
+
301
+ # -- PDF --
302
+ if suffix == ".pdf":
303
+ pages = convert_from_bytes(raw_bytes, dpi=pdf_dpi)
304
+ for page in pages:
305
+ buf = BytesIO()
306
+ page.save(buf, format="PNG")
307
+ b64 = base64.b64encode(buf.getvalue()).decode()
308
+ out.append(f"data:image/png;base64,{b64}")
309
+ continue # 进入下一文件
310
+
311
+ # -- 普通图片 --
312
+ b64 = base64.b64encode(raw_bytes).decode()
313
+ out.append(f"data:image/{suffix[1:]};base64,{b64}")
314
+
315
+ # ---------- 旧版:直接获得文件路径 ----------
316
+ else:
317
+ path = pathlib.Path(f)
318
+ suffix = path.suffix.lower()
319
+
320
+ if suffix == ".pdf":
321
+ pages = convert_from_path(str(path), dpi=pdf_dpi)
322
+ for page in pages:
323
+ buf = BytesIO()
324
+ page.save(buf, format="PNG")
325
+ b64 = base64.b64encode(buf.getvalue()).decode()
326
+ out.append(f"data:image/png;base64,{b64}")
327
+ continue
328
+
329
+ raw_bytes = path.read_bytes()
330
+ b64 = base64.b64encode(raw_bytes).decode()
331
+ out.append(f"data:image/{suffix[1:]};base64,{b64}")
332
+
333
+ return out
334
 
335
 
336
  async def process_file(file_path):
 
353
  import gradio as gr
354
  import base64, pathlib
355
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
356
 
357
 
358
  def embed_file(file, scale: float):
 
370
 
371
  # ---------- 1. PDF ----------
372
  if ext == ".pdf":
373
+
374
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
375
  else:
376
  return (
377
  f'<div style="overflow:auto;border:1px solid #ccc;'
 
403
  clear_bu = gr.ClearButton(value='Clear')
404
  pdf_show = PDF(label='Preview', interactive=False, visible=True, height=800)
405
 
 
 
 
 
 
 
406
 
407
 
408
+ with gr.Row():
409
+ prev_btn = gr.Button("⬅️ 上一张")
410
+ next_btn = gr.Button("下一张 ➡️")
411
+ zoom = gr.Slider(0.5, 3, value=1, step=0.1, label="缩放倍数")
412
+
413
+ # HTML 容器
414
+ viewer = gr.HTML()
415
+
416
+ # ---- 状态变量 ----
417
+ img_list_state = gr.State([]) # base64 列表
418
+ idx_state = gr.State(0) # 当前索引
419
+
420
+ # ---- 事件逻辑 ----
421
+ def upload_handler(files):
422
+ b64s = files_to_b64(files)
423
+ return b64s, 0, render_img(b64s, 0, 1)
424
+
425
+ file.change(
426
+ upload_handler,
427
+ inputs=file,
428
+ outputs=[img_list_state, idx_state, viewer],
429
+ )
430
+
431
+ def show_prev(b64s, idx, scale):
432
+ idx -= 1
433
+ return idx, render_img(b64s, idx, scale)
434
+
435
+ prev_btn.click(
436
+ show_prev,
437
+ inputs=[img_list_state, idx_state, zoom],
438
+ outputs=[idx_state, viewer],
439
+ )
440
+
441
+ def show_next(b64s, idx, scale):
442
+ idx += 1
443
+ return idx, render_img(b64s, idx, scale)
444
+
445
+ next_btn.click(
446
+ show_next,
447
+ inputs=[img_list_state, idx_state, zoom],
448
+ outputs=[idx_state, viewer],
449
+ )
450
+
451
+ # 缩放滑块变化
452
+ zoom.change(
453
+ lambda b64s, idx, scale: render_img(b64s, idx, scale),
454
+ inputs=[img_list_state, idx_state, zoom],
455
+ outputs=viewer,
456
+ )
457
+
458
 
459
  example_root = os.path.join(os.path.dirname(__file__), 'examples')
460
  images = [
 
505
 
506
 
507
 
508
+ # file.change(fn=process_file, inputs=file, outputs=pdf_show)
509
 
510
 
511
  change_bu.click(