Spaces:
Paused
Paused
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,70 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
import gradio as gr
|
2 |
+
import PyPDF2
|
3 |
+
import requests
|
4 |
+
import io
|
5 |
+
import os
|
6 |
+
import tempfile
|
7 |
+
|
8 |
+
def compress_pdf(input_file, url, quality):
|
9 |
+
if input_file is None and url is None:
|
10 |
+
return None, "Please provide either a file or a URL."
|
11 |
+
|
12 |
+
if input_file is not None and url is not None:
|
13 |
+
return None, "Please provide either a file or a URL, not both."
|
14 |
+
|
15 |
+
if url:
|
16 |
+
try:
|
17 |
+
response = requests.get(url)
|
18 |
+
response.raise_for_status()
|
19 |
+
pdf_content = io.BytesIO(response.content)
|
20 |
+
except requests.RequestException as e:
|
21 |
+
return None, f"Error downloading PDF: {str(e)}"
|
22 |
+
else:
|
23 |
+
pdf_content = input_file
|
24 |
+
|
25 |
+
try:
|
26 |
+
reader = PyPDF2.PdfReader(pdf_content)
|
27 |
+
writer = PyPDF2.PdfWriter()
|
28 |
+
|
29 |
+
for page in reader.pages:
|
30 |
+
if quality == "High":
|
31 |
+
page.compress_content_streams() # This is the lowest compression
|
32 |
+
elif quality == "Medium":
|
33 |
+
page.compress_content_streams(level=2)
|
34 |
+
else: # Low quality
|
35 |
+
page.compress_content_streams(level=3)
|
36 |
+
writer.add_page(page)
|
37 |
+
|
38 |
+
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
39 |
+
writer.write(temp_file)
|
40 |
+
temp_file_path = temp_file.name
|
41 |
+
|
42 |
+
return temp_file_path, "PDF compressed successfully!"
|
43 |
+
except Exception as e:
|
44 |
+
return None, f"Error compressing PDF: {str(e)}"
|
45 |
+
|
46 |
+
def process_and_compress(input_file, url, quality):
|
47 |
+
output_file, message = compress_pdf(input_file, url, quality)
|
48 |
+
if output_file:
|
49 |
+
return gr.File.update(value=output_file, visible=True), message
|
50 |
+
else:
|
51 |
+
return gr.File.update(visible=False), message
|
52 |
+
|
53 |
+
with gr.Blocks() as demo:
|
54 |
+
gr.Markdown("# PDF Compressor")
|
55 |
+
with gr.Row():
|
56 |
+
input_file = gr.File(label="Upload PDF")
|
57 |
+
url_input = gr.Textbox(label="Or enter PDF URL")
|
58 |
+
quality = gr.Radio(["High", "Medium", "Low"], label="Compression Quality", value="Medium")
|
59 |
+
compress_btn = gr.Button("Compress")
|
60 |
+
output_file = gr.File(label="Download Compressed PDF", visible=False)
|
61 |
+
message = gr.Textbox(label="Message")
|
62 |
+
|
63 |
+
compress_btn.click(
|
64 |
+
process_and_compress,
|
65 |
+
inputs=[input_file, url_input, quality],
|
66 |
+
outputs=[output_file, message]
|
67 |
+
)
|
68 |
+
|
69 |
+
if __name__ == "__main__":
|
70 |
+
demo.launch()
|