soiz1 commited on
Commit
fe2e131
·
verified ·
1 Parent(s): 5b36d3d

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +10 -6
app.py CHANGED
@@ -11,6 +11,8 @@ def downscale_pdf(pdf_file, dpi=150, max_width=1500):
11
  with tempfile.TemporaryDirectory() as tmpdir:
12
  # ステップ 1: PDF → 画像
13
  images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)
 
 
14
 
15
  downscaled_paths = []
16
  for i, img in enumerate(images):
@@ -23,20 +25,22 @@ def downscale_pdf(pdf_file, dpi=150, max_width=1500):
23
  img.save(img_path, "JPEG", quality=85)
24
  downscaled_paths.append(img_path)
25
 
 
 
 
26
  # ステップ 2: 画像 → PDF
27
  tmp_output_path = os.path.join(tmpdir, "downscaled.pdf")
28
  with open(tmp_output_path, "wb") as f_out:
29
  f_out.write(img2pdf.convert(downscaled_paths))
30
 
31
- # ここでtmpdirは消えるので、ファイルを別の場所にコピー
32
- result_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
33
- with open(tmp_output_path, "rb") as src:
34
- shutil.copyfileobj(src, result_file)
35
- result_file.close()
36
 
37
  return result_file.name
38
 
39
-
40
  with gr.Blocks() as demo:
41
  gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
42
  with gr.Row():
 
11
  with tempfile.TemporaryDirectory() as tmpdir:
12
  # ステップ 1: PDF → 画像
13
  images = convert_from_path(pdf_file.name, dpi=dpi, output_folder=tmpdir)
14
+ if not images:
15
+ raise ValueError("PDFを画像に変換できませんでした。PDFが空か、Popplerが入っていないかもしれません。")
16
 
17
  downscaled_paths = []
18
  for i, img in enumerate(images):
 
25
  img.save(img_path, "JPEG", quality=85)
26
  downscaled_paths.append(img_path)
27
 
28
+ if not downscaled_paths:
29
+ raise ValueError("変換後の画像が見つかりません。")
30
+
31
  # ステップ 2: 画像 → PDF
32
  tmp_output_path = os.path.join(tmpdir, "downscaled.pdf")
33
  with open(tmp_output_path, "wb") as f_out:
34
  f_out.write(img2pdf.convert(downscaled_paths))
35
 
36
+ # ここでtmpdirは消えるので、ファイルを残す
37
+ result_file = tempfile.NamedTemporaryFile(delete=False, suffix=".pdf")
38
+ with open(tmp_output_path, "rb") as src:
39
+ shutil.copyfileobj(src, result_file)
40
+ result_file.close()
41
 
42
  return result_file.name
43
 
 
44
  with gr.Blocks() as demo:
45
  gr.Markdown("# PDF 解像度ダウンサイザー\nPDFのページ画像を縮小して容量を減らします。")
46
  with gr.Row():