Spaces:
Sleeping
Sleeping
File size: 2,139 Bytes
3b2d5b2 49acc9d 99ee49c f1cd04c 99ee49c f1cd04c 99ee49c f1cd04c 888cd71 5b36d3d 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 |
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, dpi=150):
with tempfile.TemporaryDirectory() as tmpdir:
# ステップ 1: PDF → 画像
images = convert_from_path(pdf_file.name, dpi=300, fmt='jpeg', output_folder=tmpdir)
downscaled_images = []
for i, img in enumerate(images):
w, h = img.size
total_px = w * h
print(f"Original Page {i+1}: {w}x{h} = {total_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}")
tmp_image_path = os.path.join(tmpdir, f"page_{i+1}.jpg")
img.save(tmp_image_path, "JPEG", quality=95)
downscaled_images.append(tmp_image_path)
# ステップ 2: 画像 → PDF
output_pdf_path = os.path.join(tmpdir, "downscaled.pdf")
with open(output_pdf_path, "wb") as f:
f.write(img2pdf.convert(downscaled_images))
# ✅ Gradio返却用に一時ファイルにコピー
final_pdf_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
with open(output_pdf_path, "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()
|