Repository navigation
Expand file tree
/
Copy pathmain.py
More file actions
165 lines (133 loc) · 5.77 KB
/
Copy pathmain.py
File metadata and controls
165 lines (133 loc) · 5.77 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
import os
import math
import lzma
import gzip
import bz2
import zlib
from collections import Counter
from tqdm import tqdm
from colorama import Fore, Style, init
init(autoreset=True) # Reset automatico del colore
def calculate_entropy(byte_counter, total_bytes):
if total_bytes <= 0:
raise ValueError("Il file GGUF è vuoto: impossibile calcolare l'entropia.")
return -sum(
(freq / total_bytes) * math.log2(freq / total_bytes)
for freq in byte_counter.values()
)
def analyze_gguf(file_path):
print(f"{Fore.CYAN}--- Analisi file GGUF ---{Style.RESET_ALL}")
total_bytes = 0
byte_counter = Counter()
file_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f, tqdm(total=file_size, unit='B', unit_scale=True, desc="Analisi GGUF", colour="cyan") as pbar:
while True:
chunk = f.read(1024 * 1024)
if not chunk:
break
total_bytes += len(chunk)
byte_counter.update(chunk)
pbar.update(len(chunk))
entropy = calculate_entropy(byte_counter, total_bytes)
print(f"Dimensione originale: {file_size / (1024 ** 2):.2f} MB")
print(f"Entropia stimata: {entropy:.4f} bit per byte\n")
return {
'original_size': file_size,
'entropy_estimate': entropy
}
def compress_with_algorithm(file_path, open_func, extension, name):
print(f"{Fore.CYAN}--- Compressione file con {name} ---{Style.RESET_ALL}")
out_path = file_path + extension
file_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f_in, open_func(out_path, 'wb') as f_out, tqdm(
total=file_size, unit='B', unit_scale=True, desc=f"Compressione {name}", colour="cyan") as pbar:
while True:
chunk = f_in.read(1024 * 1024)
if not chunk:
break
f_out.write(chunk)
pbar.update(len(chunk))
compressed_size = os.path.getsize(out_path)
ratio = compressed_size / file_size
print(f"Dimensione compressa: {compressed_size / (1024 ** 2):.2f} MB")
print(f"Rapporto compressione: {ratio:.4f}\n")
return name, compressed_size, ratio
def compress_zlib(file_path):
print(f"{Fore.CYAN}--- Compressione file con ZLIB ---{Style.RESET_ALL}")
out_path = file_path + ".zlib"
file_size = os.path.getsize(file_path)
with open(file_path, 'rb') as f_in, open(out_path, 'wb') as f_out, tqdm(
total=file_size, unit='B', unit_scale=True, desc="Compressione ZLIB", colour="cyan") as pbar:
compressor = zlib.compressobj()
while True:
chunk = f_in.read(1024 * 1024)
if not chunk:
break
compressed_chunk = compressor.compress(chunk)
f_out.write(compressed_chunk)
pbar.update(len(chunk))
f_out.write(compressor.flush())
compressed_size = os.path.getsize(out_path)
ratio = compressed_size / file_size
print(f"Dimensione compressa: {compressed_size / (1024 ** 2):.2f} MB")
print(f"Rapporto compressione: {ratio:.4f}\n")
return "ZLIB", compressed_size, ratio
def print_ascii_stats(results):
print(f"{Fore.CYAN}--- Statistiche compressione ---{Style.RESET_ALL}")
print(f"{'Algoritmo':<10} | {'Dimensione (MB)':>15} | {'Rapporto':>10}")
print("-" * 42)
for name, size, ratio in results:
print(f"{name:<10} | {size / (1024 ** 2):15.2f} | {ratio:10.4f}")
print()
def main():
file_path = input("Inserisci il percorso del file .gguf: ").strip()
if not os.path.isfile(file_path):
print("File non trovato.")
return
if os.path.splitext(file_path)[1].lower() != ".gguf":
print("Il file selezionato non ha estensione .gguf.")
return
try:
analyze_gguf(file_path)
except (OSError, ValueError) as error:
print(f"Analisi non riuscita: {error}")
return
options = {
"0": ("Solo analisi", None, "Esegui solo l'analisi del file senza compressione"),
"1": ("LZMA", compress_with_algorithm, "Compressione con algoritmo LZMA (ottima compressione, lenta)"),
"2": ("GZIP", compress_with_algorithm, "Compressione GZIP (buona compatibilità e velocità)"),
"3": ("BZIP2", compress_with_algorithm, "Compressione BZIP2 (bilanciata tra velocità e compressione)"),
"4": ("ZLIB", compress_zlib, "Compressione ZLIB (veloce ma meno efficiente)"),
"5": ("Tutti", None, "Esegui tutte le compressioni disponibili")
}
print("Scegli algoritmo di compressione:")
for key, (name, _, desc) in options.items():
print(f"{key}. {name} - {desc}")
choice = input("Scelta: ").strip()
results = []
if choice == "0":
print("Eseguito solo l'analisi, nessuna compressione effettuata.")
return
elif choice == "5":
results.append(compress_with_algorithm(file_path, lzma.open, ".xz", "LZMA"))
results.append(compress_with_algorithm(file_path, gzip.open, ".gz", "GZIP"))
results.append(compress_with_algorithm(file_path, bz2.open, ".bz2", "BZIP2"))
results.append(compress_zlib(file_path))
elif choice in options and choice != "0" and choice != "5":
name, func, _ = options[choice]
if func == compress_with_algorithm:
if name == "LZMA":
results.append(compress_with_algorithm(file_path, lzma.open, ".xz", "LZMA"))
elif name == "GZIP":
results.append(compress_with_algorithm(file_path, gzip.open, ".gz", "GZIP"))
elif name == "BZIP2":
results.append(compress_with_algorithm(file_path, bz2.open, ".bz2", "BZIP2"))
else:
results.append(func(file_path))
else:
print("Scelta non valida.")
return
if results:
print_ascii_stats(results)
if __name__ == "__main__":
main()