-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPDF-toolkit.py
More file actions
1752 lines (1403 loc) · 60.9 KB
/
PDF-toolkit.py
File metadata and controls
1752 lines (1403 loc) · 60.9 KB
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
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
"""
Universal Converter + Abyss Toolkit (Tkinter Edition) - ULTIMATE FIXED VERSION
Full-featured document converter with compression, cracking, OCR, and merge tools.
Supports: CSV, XLSX, DOCX, PDF, Images, TXT
Features:
- Advanced PDF/document conversion (20+ formats)
- Batch PDF compression with quality presets
- PDF password unlock (manual + John the Ripper cracking)
- Password strength indicator with real-time feedback
- OCR for scanned PDFs
- PDF merging and manipulation
- System monitoring (CPU/RAM)
- Termux Android integration
Requirements:
pip install pandas pillow reportlab openpyxl python-docx pdf2image pypdf psutil
apt install ghostscript poppler-utils tesseract-ocr (Linux/Termux)
pkg install john # For PDF password cracking
"""
import os
import sys
import threading
import subprocess
import shutil
from datetime import datetime
import tempfile
import traceback
import re
# Tkinter
try:
import tkinter as tk
from tkinter import ttk, filedialog, messagebox, scrolledtext
except ImportError as e:
print("ERROR: Tkinter not available. Install python3-tk")
sys.exit(1)
# Optional dependencies
try:
import pandas as pd
except ImportError:
pd = None
try:
from reportlab.platypus import SimpleDocTemplate, Table, TableStyle, Paragraph
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet
REPORTLAB_AVAILABLE = True
except ImportError:
REPORTLAB_AVAILABLE = False
A4 = (595.27, 841.89)
try:
from PIL import Image, ImageDraw, ImageFont
PIL_AVAILABLE = True
except ImportError:
PIL_AVAILABLE = False
try:
import openpyxl
OPENPYXL_AVAILABLE = True
except ImportError:
OPENPYXL_AVAILABLE = False
try:
import docx
DOCX_AVAILABLE = True
except ImportError:
DOCX_AVAILABLE = False
try:
from pdf2image import convert_from_path
PDF2IMAGE_AVAILABLE = True
except ImportError:
PDF2IMAGE_AVAILABLE = False
try:
from docx2pdf import convert as docx2pdf_convert
DOCX2PDF_AVAILABLE = True
except ImportError:
DOCX2PDF_AVAILABLE = False
try:
import pypdf
PYPDF_AVAILABLE = True
except ImportError:
PYPDF_AVAILABLE = False
try:
import psutil
PSUTIL_AVAILABLE = True
except ImportError:
PSUTIL_AVAILABLE = False
# =====================================================================
# UTILITY FUNCTIONS
# =====================================================================
def now():
"""Return current time as HH:MM:SS string."""
return datetime.now().strftime("%H:%M:%S")
def log_append(log_widget, text):
"""Append text to scrolled text widget with timestamp."""
if log_widget is None:
return
try:
log_widget.configure(state='normal')
log_widget.insert(tk.END, f"[{now()}] {text}\n")
log_widget.yview_moveto(1.0)
log_widget.configure(state='disabled')
except Exception:
pass
def safe_filename(path):
"""Extract filename without extension."""
base = os.path.basename(path)
name, _ = os.path.splitext(base)
return name
def ensure_dir(path):
"""Ensure directory exists for given file path."""
directory = os.path.dirname(path)
if directory and not os.path.exists(directory):
os.makedirs(directory, exist_ok=True)
def detect_file_type(path):
"""Detect file type by extension."""
ext = os.path.splitext(path)[1].lower().strip(".")
return ext if ext else "unknown"
def check_password_strength(password):
"""
Check password strength and return (score, label, color).
Score: 0-5
"""
if not password:
return 0, "No Password", "gray"
score = 0
length = len(password)
# Length scoring
if length >= 8:
score += 1
if length >= 12:
score += 1
if length >= 16:
score += 1
# Character variety
if re.search(r'[a-z]', password):
score += 1
if re.search(r'[A-Z]', password):
score += 1
if re.search(r'[0-9]', password):
score += 1
if re.search(r'[^a-zA-Z0-9]', password):
score += 1
# Cap at 5
score = min(score, 5)
# Labels and colors
if score <= 1:
return score, "Very Weak", "red"
elif score == 2:
return score, "Weak", "orange"
elif score == 3:
return score, "Moderate", "yellow"
elif score == 4:
return score, "Strong", "lightgreen"
else:
return score, "Very Strong", "green"
def create_password_entry_with_toggle(parent, log_widget=None, with_strength=False):
"""
Create password entry with show/hide toggle button.
Returns (frame, entry, toggle_btn, [strength_label]) tuple.
"""
frame = ttk.Frame(parent)
entry = ttk.Entry(frame, show="•", width=30)
entry.pack(side='left', fill='x', expand=True, padx=(0, 5))
toggle_btn = ttk.Button(frame, text="👁", width=3)
toggle_btn.pack(side='left')
strength_label = None
if with_strength:
strength_label = ttk.Label(frame, text="", width=12)
strength_label.pack(side='left', padx=5)
def update_strength(*args):
pwd = entry.get()
score, label, color = check_password_strength(pwd)
strength_label.config(text=label, foreground=color)
entry.bind('<KeyRelease>', update_strength)
def toggle_visibility():
if entry.cget('show') == '•':
entry.config(show='')
toggle_btn.config(text="👁🗨")
else:
entry.config(show='•')
toggle_btn.config(text="👁")
toggle_btn.config(command=toggle_visibility)
if with_strength:
return frame, entry, toggle_btn, strength_label
return frame, entry, toggle_btn
# =====================================================================
# CONVERSION FUNCTIONS - DATAFRAME TO IMAGE/PDF
# =====================================================================
def df_to_image(df, out_path, log_widget=None, max_width=4096):
"""Convert pandas DataFrame to image using PIL."""
if not PIL_AVAILABLE:
raise RuntimeError("Pillow not installed. Install: pip install pillow")
if pd is None:
raise RuntimeError("Pandas not installed. Install: pip install pandas")
# Load font
try:
font = ImageFont.truetype("DejaVuSans.ttf", 16)
except Exception:
try:
font = ImageFont.truetype("/system/fonts/DroidSans.ttf", 16)
except Exception:
font = ImageFont.load_default()
pad = 10
dummy_img = Image.new("RGB", (10, 10))
draw = ImageDraw.Draw(dummy_img)
columns = list(df.columns)
rows = df.astype(str).values.tolist()
# Calculate column widths (using getbbox for Pillow 10.0+ compatibility)
col_widths = []
for i, col in enumerate(columns):
try:
# Try modern Pillow method
bbox = draw.textbbox((0, 0), str(col), font=font)
w = (bbox[2] - bbox[0]) + pad * 2
except Exception:
# Fallback for older Pillow
w = draw.textsize(str(col), font=font)[0] + pad * 2
for row in rows:
cell_text = str(row[i])
try:
bbox = draw.textbbox((0, 0), cell_text, font=font)
cell_w = (bbox[2] - bbox[0]) + pad * 2
except Exception:
cell_w = draw.textsize(cell_text, font=font)[0] + pad * 2
w = max(w, cell_w)
col_widths.append(min(w, 300)) # Max 300px per column
try:
bbox = draw.textbbox((0, 0), "Ag", font=font)
row_height = (bbox[3] - bbox[1]) + pad
except Exception:
row_height = draw.textsize("Ag", font=font)[1] + pad
header_height = row_height + 10
total_width = sum(col_widths)
total_height = header_height + row_height * len(rows)
# Scale down if too wide
if total_width > max_width:
scale = max_width / total_width
col_widths = [int(w * scale) for w in col_widths]
total_width = max_width
# Create image
img = Image.new("RGB", (total_width, total_height), "white")
draw = ImageDraw.Draw(img)
# Draw header
x = 0
for i, col in enumerate(columns):
w = col_widths[i]
draw.rectangle([x, 0, x + w, header_height], fill=(220, 220, 220), outline="black")
draw.text((x + pad, 5), str(col), font=font, fill="black")
x += w
# Draw rows
y = header_height
for row in rows:
x = 0
for i, cell in enumerate(row):
w = col_widths[i]
draw.rectangle([x, y, x + w, y + row_height], outline="black", fill="white")
cell_text = str(cell)[:50] # Truncate long text
draw.text((x + pad, y + 5), cell_text, font=font, fill="black")
x += w
y += row_height
ensure_dir(out_path)
img.save(out_path)
if log_widget:
log_append(log_widget, f"Image saved: {out_path}")
def df_to_pdf(df, out_path, log_widget=None):
"""Convert pandas DataFrame to PDF using ReportLab."""
if not REPORTLAB_AVAILABLE:
raise RuntimeError("ReportLab not installed. Install: pip install reportlab")
if pd is None:
raise RuntimeError("Pandas not installed. Install: pip install pandas")
data = [list(df.columns)]
for row in df.itertuples(index=False):
data.append([str(x) for x in row])
ensure_dir(out_path)
doc = SimpleDocTemplate(out_path, pagesize=A4)
table = Table(data, repeatRows=1)
table.setStyle(TableStyle([
('BACKGROUND', (0, 0), (-1, 0), colors.lightgrey),
('GRID', (0, 0), (-1, -1), 0.5, colors.black),
('ALIGN', (0, 0), (-1, -1), 'LEFT'),
('FONTSIZE', (0, 0), (-1, -1), 10),
('VALIGN', (0, 0), (-1, -1), 'TOP'),
]))
doc.build([table])
if log_widget:
log_append(log_widget, f"PDF saved: {out_path}")
# =====================================================================
# FORMAT-SPECIFIC CONVERSION FUNCTIONS
# =====================================================================
def csv_to_pdf(src, out, log_widget=None):
"""Convert CSV to PDF."""
if pd is None:
raise RuntimeError("Pandas required for CSV conversion")
df = pd.read_csv(src)
df_to_pdf(df, out, log_widget)
def csv_to_image(src, out, log_widget=None):
"""Convert CSV to image."""
if pd is None:
raise RuntimeError("Pandas required for CSV conversion")
df = pd.read_csv(src)
df_to_image(df, out, log_widget)
def csv_to_xlsx(src, out, log_widget=None):
"""Convert CSV to XLSX."""
if pd is None:
raise RuntimeError("Pandas required for CSV conversion")
df = pd.read_csv(src)
ensure_dir(out)
df.to_excel(out, index=False)
if log_widget:
log_append(log_widget, f"XLSX saved: {out}")
def xlsx_to_pdf(src, out, log_widget=None):
"""Convert XLSX to PDF."""
if pd is None:
raise RuntimeError("Pandas required for XLSX conversion")
df = pd.read_excel(src)
df_to_pdf(df, out, log_widget)
def xlsx_to_image(src, out, log_widget=None):
"""Convert XLSX to image."""
if pd is None:
raise RuntimeError("Pandas required for XLSX conversion")
df = pd.read_excel(src)
df_to_image(df, out, log_widget)
def xlsx_to_csv(src, out, log_widget=None):
"""Convert XLSX to CSV."""
if pd is None:
raise RuntimeError("Pandas required for XLSX conversion")
df = pd.read_excel(src)
ensure_dir(out)
df.to_csv(out, index=False)
if log_widget:
log_append(log_widget, f"CSV saved: {out}")
def txt_to_pdf(src, out, log_widget=None):
"""Convert text file to PDF."""
if not REPORTLAB_AVAILABLE:
raise RuntimeError("ReportLab required for TXT to PDF conversion")
with open(src, 'r', encoding='utf-8', errors='ignore') as f:
text = f.read()
ensure_dir(out)
doc = SimpleDocTemplate(out, pagesize=A4)
styles = getSampleStyleSheet()
# Replace newlines with HTML breaks
text_html = text.replace('\n', '<br/>')
para = Paragraph(text_html, styles["Normal"])
doc.build([para])
if log_widget:
log_append(log_widget, f"PDF saved: {out}")
def image_to_pdf(src, out, log_widget=None):
"""Convert image to PDF."""
if not PIL_AVAILABLE:
raise RuntimeError("Pillow required for image conversion")
img = Image.open(src)
if img.mode == "RGBA":
img = img.convert("RGB")
ensure_dir(out)
img.save(out, "PDF")
if log_widget:
log_append(log_widget, f"PDF saved: {out}")
def pdf_to_images(src, out_dir, log_widget=None):
"""Convert PDF pages to images."""
if not PDF2IMAGE_AVAILABLE:
raise RuntimeError("pdf2image not installed. Install: pip install pdf2image")
ensure_dir(out_dir)
try:
pages = convert_from_path(src)
outfiles = []
for i, page in enumerate(pages, 1):
out_path = os.path.join(out_dir, f"{safe_filename(src)}_page_{i}.png")
page.save(out_path, "PNG")
outfiles.append(out_path)
if log_widget:
log_append(log_widget, f"Extracted page {i}")
return outfiles
except Exception as e:
raise RuntimeError(f"PDF extraction failed: {e}")
def docx_to_pdf(src, out, log_widget=None):
"""Convert DOCX to PDF."""
# Try docx2pdf first (Windows compatible)
if DOCX2PDF_AVAILABLE:
try:
tmp_dir = tempfile.mkdtemp()
docx2pdf_convert(src, tmp_dir)
produced = os.path.join(tmp_dir, safe_filename(src) + ".pdf")
if os.path.exists(produced):
ensure_dir(out)
shutil.move(produced, out)
shutil.rmtree(tmp_dir, ignore_errors=True)
if log_widget:
log_append(log_widget, f"PDF saved: {out}")
return
except Exception as e:
if log_widget:
log_append(log_widget, f"docx2pdf failed: {e}")
# Try LibreOffice
if shutil.which("soffice"):
try:
tmp_dir = tempfile.mkdtemp()
cmd = ["soffice", "--headless", "--convert-to", "pdf", "--outdir", tmp_dir, src]
subprocess.run(cmd, check=True, capture_output=True)
produced = os.path.join(tmp_dir, safe_filename(src) + ".pdf")
if os.path.exists(produced):
ensure_dir(out)
shutil.move(produced, out)
shutil.rmtree(tmp_dir, ignore_errors=True)
if log_widget:
log_append(log_widget, f"PDF saved: {out}")
return
except Exception as e:
if log_widget:
log_append(log_widget, f"LibreOffice conversion failed: {e}")
# Fallback: extract text and create simple PDF
if not DOCX_AVAILABLE:
raise RuntimeError("python-docx not installed. Install: pip install python-docx")
document = docx.Document(src)
paragraphs = "\n".join([p.text for p in document.paragraphs])
txt_file = os.path.join(tempfile.gettempdir(), "tmp_docx.txt")
with open(txt_file, "w", encoding='utf-8') as f:
f.write(paragraphs)
txt_to_pdf(txt_file, out, log_widget)
def docx_to_images(src, out_dir, log_widget=None):
"""Convert DOCX to images via PDF."""
tmp_pdf = os.path.join(tempfile.gettempdir(), safe_filename(src) + "_tmp.pdf")
docx_to_pdf(src, tmp_pdf, log_widget)
return pdf_to_images(tmp_pdf, out_dir, log_widget)
# =====================================================================
# PDF PASSWORD FUNCTIONS
# =====================================================================
def unlock_pdf_manual(pdf_path, password, log_widget):
"""
Unlock a password-protected PDF using known password.
Returns path to unlocked PDF.
"""
if not PYPDF_AVAILABLE:
raise RuntimeError("pypdf not installed. Install: pip install pypdf")
try:
log_append(log_widget, f"Attempting to unlock: {os.path.basename(pdf_path)}")
reader = pypdf.PdfReader(pdf_path)
# Check if encrypted
if not reader.is_encrypted:
log_append(log_widget, "PDF is not encrypted")
messagebox.showinfo("Not Encrypted", "This PDF is not password-protected")
return None
# Try to decrypt
if not reader.decrypt(password):
log_append(log_widget, "❌ Incorrect password")
return None
log_append(log_widget, "✔ Password correct, creating unlocked version...")
# Create unlocked version
writer = pypdf.PdfWriter()
for page in reader.pages:
writer.add_page(page)
# Generate output path
base = os.path.splitext(pdf_path)[0]
out_path = f"{base}_unlocked.pdf"
# Handle file exists
counter = 1
while os.path.exists(out_path):
out_path = f"{base}_unlocked_{counter}.pdf"
counter += 1
ensure_dir(out_path)
with open(out_path, "wb") as output_file:
writer.write(output_file)
log_append(log_widget, f"✔ Unlocked PDF saved: {out_path}")
return out_path
except Exception as e:
log_append(log_widget, f"❌ Unlock failed: {e}")
return None
def crack_pdf_with_john(pdf_path, wordlist, log_widget):
"""
Attempt to crack PDF password using John the Ripper.
Handles pdf2john, pdf2john.py, pdf2john.pl across Termux/Linux/macOS.
"""
# Try to find pdf2john in multiple forms
pdf2john_cmd = None
# Check common locations and names
candidates = [
"pdf2john", # Most common (symlink or Python version)
"pdf2john.py", # Explicit Python version
"pdf2john.pl", # Perl version (older)
"/data/data/com.termux/files/usr/share/john/pdf2john.py", # Termux Python
"/data/data/com.termux/files/usr/share/john/pdf2john.pl", # Termux Perl
"/usr/share/john/pdf2john.py", # Linux Python
"/usr/share/john/pdf2john.pl", # Linux Perl
]
for candidate in candidates:
if os.path.exists(candidate):
pdf2john_cmd = candidate
break
elif shutil.which(candidate):
pdf2john_cmd = candidate
break
if not pdf2john_cmd:
log_append(log_widget, "❌ pdf2john not found. Install: pkg install john")
return None
log_append(log_widget, f"Using: {pdf2john_cmd}")
hash_file = pdf_path + ".hash"
# Extract hash
try:
log_append(log_widget, "Extracting PDF hash...")
# Handle Python vs Perl versions
if pdf2john_cmd.endswith(".py"):
cmd = ["python3", pdf2john_cmd, pdf_path]
elif pdf2john_cmd.endswith(".pl"):
cmd = ["perl", pdf2john_cmd, pdf_path]
else:
cmd = [pdf2john_cmd, pdf_path]
with open(hash_file, "w") as hf:
result = subprocess.run(cmd, stdout=hf, stderr=subprocess.PIPE, text=True)
if result.returncode != 0:
log_append(log_widget, f"Hash extraction failed: {result.stderr}")
return None
except Exception as e:
log_append(log_widget, f"Hash extraction error: {e}")
return None
# Verify hash file exists and has content
if not os.path.exists(hash_file) or os.path.getsize(hash_file) == 0:
log_append(log_widget, "❌ Hash file empty. PDF may not be encrypted.")
return None
# Run John the Ripper
john_cmd = ["john", hash_file]
if wordlist and os.path.exists(wordlist):
john_cmd.append(f"--wordlist={wordlist}")
log_append(log_widget, f"Using wordlist: {os.path.basename(wordlist)}")
else:
log_append(log_widget, "No wordlist — using default John modes")
try:
log_append(log_widget, "🔥 Running John the Ripper...")
proc = subprocess.Popen(
john_cmd,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT,
text=True
)
for line in proc.stdout:
log_append(log_widget, f"JOHN: {line.rstrip()}")
proc.wait()
# Show cracked passwords
result = subprocess.run(
["john", "--show", hash_file],
capture_output=True,
text=True
)
for line in result.stdout.splitlines():
if ":" in line and not line.startswith("0 password"):
parts = line.split(":")
if len(parts) >= 2:
password = parts[1].strip()
log_append(log_widget, f"🔑 PASSWORD FOUND: {password}")
return password
log_append(log_widget, "❌ No password found")
return None
except FileNotFoundError:
log_append(log_widget, "❌ 'john' command not found. Install: pkg install john")
return None
except Exception as e:
log_append(log_widget, f"Cracking error: {e}")
return None
finally:
# Cleanup hash file
if os.path.exists(hash_file):
try:
os.remove(hash_file)
except Exception:
pass
# =====================================================================
# ABYSS TOOLKIT FUNCTIONS
# =====================================================================
def compress_pdf_list(file_list, dpi, log_widget, delete_original=False):
"""Compress PDFs using Ghostscript."""
dpi_setting = str(int(dpi))
for file_path in file_list:
base, ext = os.path.splitext(file_path)
out_path = f"{base}_compressed{ext}"
counter = 1
final_out_path = out_path
while os.path.exists(final_out_path):
final_out_path = f"{base}_compressed_{counter}{ext}"
counter += 1
cmd = [
"gs", "-sDEVICE=pdfwrite", "-dCompatibilityLevel=1.4",
"-dPDFSETTINGS=/ebook", # Use a base setting
f"-dColorImageResolution={dpi_setting}",
f"-dGrayImageResolution={dpi_setting}",
f"-dMonoImageResolution={dpi_setting}",
"-dColorImageDownsampleType=/Bicubic",
"-dGrayImageDownsampleType=/Bicubic",
"-dMonoImageDownsampleType=/Bicubic",
"-dNOPAUSE", "-dQUIET", "-dBATCH",
f"-sOutputFile={final_out_path}", file_path
]
log_append(log_widget, f"Compressing: {os.path.basename(file_path)}")
try:
# Run Ghostscript
result = subprocess.run(cmd, check=True, capture_output=True, text=True)
log_append(log_widget, f"Saved: {final_out_path}")
# Delete original if requested and compression was successful
if delete_original:
try:
os.remove(file_path)
log_append(log_widget, f"Deleted original: {os.path.basename(file_path)}")
except OSError as e:
log_append(log_widget, f"Failed to delete {os.path.basename(file_path)}: {e}")
except subprocess.CalledProcessError as e:
log_append(log_widget, f"Compression failed for {os.path.basename(file_path)}: {e.stderr}")
except FileNotFoundError:
log_append(log_widget, "Ghostscript not found. Install: apt install ghostscript")
break
def merge_pdfs(pdf_list, out_path, log_widget):
"""Merge multiple PDFs into one."""
if not PYPDF_AVAILABLE:
raise RuntimeError("pypdf not installed. Install: pip install pypdf")
writer = pypdf.PdfWriter()
for pdf_path in pdf_list:
try:
writer.append(pdf_path)
log_append(log_widget, f"Appended: {os.path.basename(pdf_path)}")
except Exception as e:
log_append(log_widget, f"Failed to append {pdf_path}: {e}")
ensure_dir(out_path)
with open(out_path, "wb") as output_file:
writer.write(output_file)
log_append(log_widget, f"Merged PDF saved: {out_path}")
return out_path
def run_ocrmypdf(src, out, log_widget):
"""Run OCR on PDF using ocrmypdf."""
if not shutil.which("ocrmypdf"):
raise RuntimeError("ocrmypdf not found. Install: pip install ocrmypdf")
cmd = ["ocrmypdf", "--force-ocr", src, out]
log_append(log_widget, "Starting OCR process...")
try:
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
log_append(log_widget, f"OCR completed: {out}")
else:
log_append(log_widget, f"OCR error: {result.stderr}")
except Exception as e:
log_append(log_widget, f"OCR failed: {e}")
raise
def termux_share_file(path, log_widget):
"""Share file using Termux API."""
if shutil.which("termux-share"):
subprocess.Popen(["termux-share", "-a", "send", path])
log_append(log_widget, f"Shared via Termux: {path}")
else:
log_append(log_widget, "termux-share not found")
# =====================================================================
# MAIN APPLICATION
# =====================================================================
class ConverterApp(tk.Tk):
"""Main application window."""
def __init__(self):
super().__init__()
self.title("Universal Converter + Abyss Toolkit")
self.minsize(700, 500)
self.last_output = None
self._abyss_injected = False
self.compress_file_count = tk.StringVar(value="Files: 0")
self.compress_total_size = tk.StringVar(value="Total Size: 0 MB")
self.compress_est_size = tk.StringVar(value="Est. Size: 0 MB")
self.compress_est_time = tk.StringVar(value="Est. Time: 0s")
self.create_ui()
self.after(500, self.inject_abyss_features)
def create_ui(self):
"""Create main UI layout."""
# Title bar
title_frame = ttk.Frame(self)
title_frame.pack(fill='x', padx=8, pady=6)
ttk.Label(
title_frame,
text="UNIVERSAL CONVERTER TOOLKIT",
font=("Arial", 16, "bold")
).pack(side='left')
# System stats (will be populated later)
self.stats_frame = ttk.Frame(title_frame)
self.stats_frame.pack(side='right')
# Notebook (tabs)
self.notebook = ttk.Notebook(self)
self.notebook.pack(fill='both', expand=True, padx=10, pady=10)
# Create tabs
self.tab_convert = ttk.Frame(self.notebook)
self.tab_compress = ttk.Frame(self.notebook)
self.tab_crack = ttk.Frame(self.notebook)
self.tab_tools = ttk.Frame(self.notebook)
self.tab_update = ttk.Frame(self.notebook)
self.notebook.add(self.tab_convert, text="Convert")
self.notebook.add(self.tab_compress, text="Compress")
self.notebook.add(self.tab_crack, text="Crack")
self.notebook.add(self.tab_tools, text="Tools")
# self.notebook.add(self.tab_update, text="Update")
# Build Convert tab
self.build_convert_tab()
# Placeholder labels for other tabs (will be built by inject_abyss_features)
ttk.Label(self.tab_compress, text="Loading...").pack(pady=20)
ttk.Label(self.tab_crack, text="Loading...").pack(pady=20)
ttk.Label(self.tab_tools, text="Loading...").pack(pady=20)
# Global log
log_frame = ttk.LabelFrame(self, text="SYSTEM LOG")
log_frame.pack(fill='both', expand=True, padx=10, pady=10)
self.log_widget = scrolledtext.ScrolledText(
log_frame,
height=12,
state='disabled',
bg="#111111",
fg="#00ff00",
font=("Courier", 9)
)
self.log_widget.pack(fill='both', expand=True, padx=5, pady=5)
def build_convert_tab(self):
"""Build the Convert tab UI."""
container = ttk.Frame(self.tab_convert)
container.pack(fill='both', expand=True, padx=10, pady=10)
# Input file selection
input_frame = ttk.Frame(container)
input_frame.pack(fill='x', pady=5)
ttk.Label(input_frame, text="Input File:").pack(side='left')
self.input_entry = ttk.Entry(input_frame)
self.input_entry.pack(side='left', fill='x', expand=True, padx=8)
ttk.Button(input_frame, text="Browse", command=self.browse_input).pack(side='left')
# Detected type
type_frame = ttk.Frame(container)
type_frame.pack(fill='x', pady=5)
ttk.Label(type_frame, text="Detected Type:").pack(side='left')
self.type_label = ttk.Label(type_frame, text="None", foreground="blue")
self.type_label.pack(side='left', padx=8)
# Output options
output_frame = ttk.Frame(container)
output_frame.pack(fill='x', pady=5)
ttk.Label(output_frame, text="Output Format:").pack(side='left')
self.format_combo = ttk.Combobox(
output_frame,
values=["pdf", "png", "jpg", "xlsx", "csv"],
state='readonly',
width=10
)
self.format_combo.set("pdf")
self.format_combo.pack(side='left', padx=8)
ttk.Label(output_frame, text="Output Folder:").pack(side='left', padx=(20, 0))
self.output_folder_entry = ttk.Entry(output_frame, width=25)
self.output_folder_entry.pack(side='left', padx=8)
ttk.Button(output_frame, text="Pick Folder", command=self.browse_output).pack(side='left')
# Convert button
button_frame = ttk.Frame(container)
button_frame.pack(fill='x', pady=10)
self.convert_button = ttk.Button(
button_frame,
text="CONVERT",
command=self.start_conversion
)
self.convert_button.pack(side='left')
ttk.Button(
button_frame,
text="Open Output Folder",
command=self.open_output_folder
).pack(side='left', padx=10)
# Results list
results_frame = ttk.LabelFrame(container, text="Output Files")
results_frame.pack(fill='both', expand=True, pady=10)
self.results_listbox = tk.Listbox(results_frame, height=10)
self.results_listbox.pack(fill='both', expand=True, padx=5, pady=5)
def browse_input(self):
"""Browse for input file."""
filename = filedialog.askopenfilename(title="Select input file")
if filename:
self.input_entry.delete(0, tk.END)
self.input_entry.insert(0, filename)
file_type = detect_file_type(filename)
self.type_label.config(text=file_type.upper())
log_append(self.log_widget, f"Selected: {os.path.basename(filename)} ({file_type})")
def browse_output(self):
"""Browse for output folder."""
folder = filedialog.askdirectory(title="Select output folder")
if folder:
self.output_folder_entry.delete(0, tk.END)
self.output_folder_entry.insert(0, folder)
def open_output_folder(self):
"""Open output folder in file manager."""
folder = self.output_folder_entry.get().strip()
if not folder or not os.path.exists(folder):
messagebox.showwarning("Warning", "Output folder does not exist")
return
if sys.platform.startswith("win"):
os.startfile(folder)
elif sys.platform.startswith("darwin"):
subprocess.Popen(["open", folder])
else:
subprocess.Popen(["xdg-open", folder])
def start_conversion(self):
"""Start conversion process in background thread."""
input_file = self.input_entry.get().strip()
if not input_file or not os.path.exists(input_file):
messagebox.showerror("Error", "Please select a valid input file")
return
output_format = self.format_combo.get().lower()
output_folder = self.output_folder_entry.get().strip()
if not output_folder:
output_folder = os.path.dirname(input_file)
self.convert_button.config(state='disabled')
self.results_listbox.delete(0, tk.END)
thread = threading.Thread(
target=self.conversion_worker,
args=(input_file, output_format, output_folder),
daemon=True
)