Spaces:
Sleeping
Sleeping
File size: 2,719 Bytes
3b2d5b2 49acc9d 99ee49c 03f50bc 99ee49c 03f50bc 99ee49c 8253852 99ee49c 8253852 99ee49c 8253852 03f50bc f1cd04c 03f50bc f1cd04c 888cd71 03f50bc 888cd71 5b36d3d 03f50bc 49acc9d 99ee49c f1cd04c 99ee49c f1cd04c 49acc9d 99ee49c 3b2d5b2 99ee49c |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 |
import gradio as gr
from pdf2image import convert_from_path
from PIL import Image
import img2pdf
import tempfile
import os
def downscale_pdf(pdf_file, max_width=3000, input_dpi=150):
with tempfile.TemporaryDirectory() as tmpdir:
# 1. dpiを下げて読み込み(元が300なら150に半減)
images = convert_from_path(pdf_file.name, dpi=input_dpi, fmt='jpeg', output_folder=tmpdir)
downscaled_images = []
for i, img in enumerate(images):
w, h = img.size
print(f"Original Page {i+1}: {w}x{h} = {w * h} px")
# サイズ制限
if w > max_width:
ratio = max_width / w
new_w = int(w * ratio)
new_h = int(h * ratio)
img = img.resize((new_w, new_h), Image.LANCZOS)
print(f"Downscaled Page {i+1}: {new_w}x{new_h} = {new_w * new_h} px")
else:
new_w, new_h = w, h
print(f"Page {i+1}: サイズ変更なし")
tmp_image_path = os.path.join(tmpdir, f"page_{i+1}.jpg")
img.save(tmp_image_path, "JPEG", quality=90)
downscaled_images.append((tmp_image_path, (new_w, new_h)))
# 2. img2pdfのdpiを画像サイズから計算する
# dpi = (元画像のdpi) * (縮小率)
# 今回は画像のピクセル数が縮小されているので、それに対応するdpiを設定する
# ここでは単純に input_dpi をそのまま使うことも可
pdf_bytes = b""
layout_fun = img2pdf.get_layout_fun(pagesize=None) # デフォルトページサイズ
with open(os.path.join(tmpdir, "downscaled.pdf"), "wb") as f:
f.write(
img2pdf.convert(
[path for path, size in downscaled_images],
dpi=input_dpi,
)
)
final_pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
with open(os.path.join(tmpdir, "downscaled.pdf"), "rb") as src, open(final_pdf_file.name, "wb") as dst:
dst.write(src.read())
return final_pdf_file.name
with gr.Blocks() as demo:
gr.Markdown("## PDFダウンサイザー for Audiveris")
gr.Markdown(
"PDFをアップロードすると、ページ画像を縮小してAudiveris向けに最適化したPDFを生成します。"
)
with gr.Row():
pdf_input = gr.File(label="PDFファイルをアップロード")
pdf_output = gr.File(label="変換後PDF")
convert_button = gr.Button("変換してダウンロード")
convert_button.click(fn=downscale_pdf, inputs=pdf_input, outputs=pdf_output)
demo.launch()
|