Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
@@ -1,40 +1,53 @@
|
|
1 |
import gradio as gr
|
2 |
-
import subprocess
|
3 |
-
import os
|
4 |
import tempfile
|
|
|
|
|
|
|
|
|
5 |
|
6 |
-
def
|
7 |
with tempfile.TemporaryDirectory() as tmpdir:
|
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 |
demo.launch()
|
|
|
1 |
import gradio as gr
|
|
|
|
|
2 |
import tempfile
|
3 |
+
from pdf2image import convert_from_path
|
4 |
+
from PIL import Image
|
5 |
+
import img2pdf
|
6 |
+
import os
|
7 |
|
8 |
+
def downscale_pdf(pdf_file, dpi=150, max_width=1500):
|
9 |
with tempfile.TemporaryDirectory() as tmpdir:
|
10 |
+
# ステップ 1: PDF → 画像(dpiを指定)
|
11 |
+
images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)
|
12 |
+
|
13 |
+
downscaled_paths = []
|
14 |
+
|
15 |
+
for i, img in enumerate(images):
|
16 |
+
# ステップ 2: サイズを制限
|
17 |
+
w, h = img.size
|
18 |
+
if w > max_width:
|
19 |
+
new_h = int(h * max_width / w)
|
20 |
+
img = img.resize((max_width, new_h), Image.LANCZOS)
|
21 |
+
|
22 |
+
# 一時保存
|
23 |
+
img_path = os.path.join(tmpdir, f"page_{i}.jpg")
|
24 |
+
img.save(img_path, "JPEG", quality=85)
|
25 |
+
downscaled_paths.append(img_path)
|
26 |
+
|
27 |
+
# ステップ 3: 画像をPDFに再結合
|
28 |
+
output_pdf_path = os.path.join(tmpdir, "downscaled.pdf")
|
29 |
+
with open(output_pdf_path, "wb") as f_out:
|
30 |
+
f_out.write(img2pdf.convert(downscaled_paths))
|
31 |
+
|
32 |
+
# 返却
|
33 |
+
return output_pdf_path
|
34 |
+
|
35 |
+
with gr.Blocks() as demo:
|
36 |
+
gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
|
37 |
+
with gr.Row():
|
38 |
+
with gr.Column():
|
39 |
+
pdf_input = gr.File(label="入力PDF", file_types=[".pdf"])
|
40 |
+
dpi_input = gr.Slider(72, 300, value=150, step=1, label="変換DPI")
|
41 |
+
width_input = gr.Slider(500, 3000, value=1500, step=50, label="最大幅(px)")
|
42 |
+
convert_button = gr.Button("変換")
|
43 |
+
|
44 |
+
with gr.Column():
|
45 |
+
pdf_output = gr.File(label="出力PDF")
|
46 |
+
|
47 |
+
convert_button.click(
|
48 |
+
fn=downscale_pdf,
|
49 |
+
inputs=[pdf_input, dpi_input, width_input],
|
50 |
+
outputs=pdf_output
|
51 |
+
)
|
52 |
|
53 |
demo.launch()
|