NeuroDong commited on
Commit
cf8d232
·
1 Parent(s): cf1eda9

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +24 -2
app.py CHANGED
@@ -72,8 +72,30 @@ def convert_pdf(pdf_file, pages="all", dpi=DEFAULT_DPI):
72
  if pdf_file is None:
73
  raise gr.Error("请上传 PDF 文件")
74
 
75
- # 读取 PDF bytes 并渲染为图像
76
- pdf_bytes = pdf_file.read()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
77
  images_all = rasterize_pages(pdf_bytes, dpi=int(dpi))
78
 
79
  # 页码选择与限制
 
72
  if pdf_file is None:
73
  raise gr.Error("请上传 PDF 文件")
74
 
75
+ # 读取 PDF bytes 并兼容 gradio 不同版本的返回值(file-like / dict / 有 name 属性 / 路径)
76
+ pdf_bytes = None
77
+ if hasattr(pdf_file, "read"): # file-like object
78
+ pdf_bytes = pdf_file.read()
79
+ elif isinstance(pdf_file, dict) and "name" in pdf_file: # gradio 有时返回 dict {'name': path}
80
+ with open(pdf_file["name"], "rb") as f:
81
+ pdf_bytes = f.read()
82
+ elif hasattr(pdf_file, "name") and isinstance(pdf_file.name, str): # object with .name path
83
+ with open(pdf_file.name, "rb") as f:
84
+ pdf_bytes = f.read()
85
+ else:
86
+ # 兜底:尝试把对象当作路径处理
87
+ try:
88
+ p = str(pdf_file)
89
+ if os.path.exists(p):
90
+ with open(p, "rb") as f:
91
+ pdf_bytes = f.read()
92
+ except Exception:
93
+ pdf_bytes = None
94
+
95
+ if pdf_bytes is None:
96
+ raise gr.Error("无法读取上传的 PDF 文件(不支持的文件对象类型)")
97
+
98
+ # 渲染 PDF 为图像
99
  images_all = rasterize_pages(pdf_bytes, dpi=int(dpi))
100
 
101
  # 页码选择与限制