Fix file preview: Use PDF format for preview component with temp files
Browse files
app.py
CHANGED
@@ -484,22 +484,19 @@ with gr.Blocks(css=custom_css, title="Dolphin Document Parser") as demo:
|
|
484 |
|
485 |
# 事件处理 - 预览文件
|
486 |
def preview_file(file_path):
|
487 |
-
"""
|
488 |
if file_path is None:
|
489 |
return None
|
490 |
|
491 |
-
|
492 |
-
|
493 |
-
try:
|
494 |
-
# 转换PDF第一页为图像
|
495 |
-
converted_path = convert_to_image(file_path, target_size=896)
|
496 |
-
return converted_path
|
497 |
-
except Exception as e:
|
498 |
-
logger.error(f"Error converting PDF for preview: {e}")
|
499 |
return file_path
|
500 |
-
|
501 |
-
|
502 |
-
|
|
|
|
|
|
|
503 |
|
504 |
file.change(fn=preview_file, inputs=file, outputs=pdf_show)
|
505 |
|
|
|
484 |
|
485 |
# 事件处理 - 预览文件
|
486 |
def preview_file(file_path):
|
487 |
+
"""预览上传的文件,转换为PDF格式用于预览组件"""
|
488 |
if file_path is None:
|
489 |
return None
|
490 |
|
491 |
+
with pymupdf.open(file_path) as f:
|
492 |
+
if f.is_pdf:
|
|
|
|
|
|
|
|
|
|
|
|
|
493 |
return file_path
|
494 |
+
else:
|
495 |
+
pdf_bytes = f.convert_to_pdf()
|
496 |
+
# 使用临时文件保存PDF
|
497 |
+
with tempfile.NamedTemporaryFile(suffix=".pdf", delete=False) as tmp_file:
|
498 |
+
tmp_file.write(pdf_bytes)
|
499 |
+
return tmp_file.name
|
500 |
|
501 |
file.change(fn=preview_file, inputs=file, outputs=pdf_show)
|
502 |
|