Spaces:
Paused
Paused
Update app.py
Browse files
app.py
CHANGED
@@ -42,15 +42,13 @@ def compress_pdf(input_file, url, strength):
|
|
42 |
else: # High
|
43 |
target_ratio = 0.25 # 75% compression
|
44 |
|
45 |
-
#
|
46 |
for page in reader.pages:
|
47 |
page.compress_content_streams() # Apply content stream compression
|
48 |
writer.add_page(page)
|
49 |
|
50 |
# Set compression parameters
|
51 |
writer.compress = True
|
52 |
-
writer._compress_streams = True
|
53 |
-
writer._compress_pages = True
|
54 |
|
55 |
# Write the compressed PDF to a temporary file
|
56 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
@@ -59,30 +57,13 @@ def compress_pdf(input_file, url, strength):
|
|
59 |
|
60 |
# Check the compression ratio achieved
|
61 |
compressed_size = os.path.getsize(temp_file_path)
|
62 |
-
|
|
|
63 |
|
64 |
-
# If
|
65 |
-
if
|
66 |
-
|
67 |
-
|
68 |
-
|
69 |
-
for page in reader.pages:
|
70 |
-
# Apply more aggressive compression
|
71 |
-
page.compress_content_streams()
|
72 |
-
writer.add_page(page)
|
73 |
-
|
74 |
-
writer.compress = True
|
75 |
-
writer._compress_streams = True
|
76 |
-
writer._compress_pages = True
|
77 |
-
|
78 |
-
# Overwrite the temporary file with the more compressed version
|
79 |
-
with open(temp_file_path, 'wb') as temp_file:
|
80 |
-
writer.write(temp_file)
|
81 |
-
|
82 |
-
# Final compression ratio
|
83 |
-
final_size = os.path.getsize(temp_file_path)
|
84 |
-
final_ratio = final_size / initial_size
|
85 |
-
compression_percentage = (1 - final_ratio) * 100
|
86 |
|
87 |
return temp_file_path, f"PDF compressed successfully! Compression achieved: {compression_percentage:.2f}%"
|
88 |
except Exception as e:
|
|
|
42 |
else: # High
|
43 |
target_ratio = 0.25 # 75% compression
|
44 |
|
45 |
+
# Apply compression to each page
|
46 |
for page in reader.pages:
|
47 |
page.compress_content_streams() # Apply content stream compression
|
48 |
writer.add_page(page)
|
49 |
|
50 |
# Set compression parameters
|
51 |
writer.compress = True
|
|
|
|
|
52 |
|
53 |
# Write the compressed PDF to a temporary file
|
54 |
with tempfile.NamedTemporaryFile(delete=False, suffix=".pdf") as temp_file:
|
|
|
57 |
|
58 |
# Check the compression ratio achieved
|
59 |
compressed_size = os.path.getsize(temp_file_path)
|
60 |
+
compression_ratio = compressed_size / initial_size
|
61 |
+
compression_percentage = (1 - compression_ratio) * 100
|
62 |
|
63 |
+
# If compression increased file size or didn't meet minimum threshold, return original file
|
64 |
+
if compression_ratio >= 1 or compression_percentage < 5:
|
65 |
+
os.remove(temp_file_path)
|
66 |
+
return input_file, f"Unable to compress the PDF effectively. Original file returned. (Attempted compression: {compression_percentage:.2f}%)"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
67 |
|
68 |
return temp_file_path, f"PDF compressed successfully! Compression achieved: {compression_percentage:.2f}%"
|
69 |
except Exception as e:
|