-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmetapython.py
More file actions
393 lines (326 loc) · 13.9 KB
/
metapython.py
File metadata and controls
393 lines (326 loc) · 13.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
import grp
import hashlib
import json
import os
import pwd
import shutil
import stat
import subprocess
from datetime import datetime
import magic
from PIL import Image, ImageFile
from PIL.ExifTags import TAGS, GPSTAGS
ImageFile.LOAD_TRUNCATED_IMAGES = True
def get_file_metadata(filepath):
try:
info = os.stat(filepath)
try:
owner = pwd.getpwuid(info.st_uid).pw_name
except KeyError:
owner = info.st_uid
try:
group = grp.getgrgid(info.st_gid).gr_name
except KeyError:
group = info.st_gid
mime = magic.Magic(mime=True)
file_type = mime.from_file(filepath)
specific_metadata = get_specific_metadata(filepath, file_type)
metadata = {
'Nombre': os.path.basename(filepath),
'Ruta absoluta': os.path.abspath(filepath),
'Tamaño': f"{info.st_size} bytes",
'Tipo MIME': file_type,
'Tipo': 'Directorio' if stat.S_ISDIR(info.st_mode) else 'Archivo',
'Permisos (numérico)': oct(stat.S_IMODE(info.st_mode)),
'Permisos (simbólico)': mode_to_str(info.st_mode),
'Inodo': info.st_ino,
'Dispositivo': info.st_dev,
'Número de enlaces duros': info.st_nlink,
'ID de usuario propietario': info.st_uid,
'Nombre de usuario propietario': owner,
'ID de grupo propietario': info.st_gid,
'Nombre de grupo propietario': group,
'Último acceso': datetime.fromtimestamp(info.st_atime).strftime('%Y-%m-%d %H:%M:%S'),
'Última modificación': datetime.fromtimestamp(info.st_mtime).strftime('%Y-%m-%d %H:%M:%S'),
'Último cambio de metadatos': datetime.fromtimestamp(info.st_ctime).strftime('%Y-%m-%d %H:%M:%S'),
'Tamaño en disco': f"{(info.st_blocks * 512)} bytes",
'SHA-256': calculate_hash(filepath),
}
metadata.update(specific_metadata)
return metadata
except Exception as e:
return {"Error": f"No se pudo obtener la información del archivo: {str(e)}"}
def get_specific_metadata(filepath, file_type):
if file_type.startswith('image/'):
return get_image_metadata(filepath)
elif file_type in ['application/pdf', 'application/msword',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document']:
return get_document_metadata(filepath)
elif file_type.startswith(('audio/', 'video/')):
return get_media_metadata(filepath)
return {}
def get_decimal_from_dms(dms, ref):
degrees = dms[0].numerator / dms[0].denominator
minutes = dms[1].numerator / (dms[1].denominator * 60.0)
seconds = dms[2].numerator / (dms[2].denominator * 3600.0)
decimal = degrees + minutes + seconds
if ref in ['S', 'W']:
decimal = -decimal
return decimal
def get_gps_info(exif_data):
try:
gps_info = {}
for key in exif_data.keys():
if key in GPSTAGS:
gps_info[GPSTAGS[key]] = exif_data[key]
if not gps_info:
return None
gps_data = {}
if 'GPSLatitude' in gps_info and 'GPSLatitudeRef' in gps_info:
gps_data['Latitud'] = get_decimal_from_dms(
gps_info['GPSLatitude'],
gps_info['GPSLatitudeRef']
)
if 'GPSLongitude' in gps_info and 'GPSLongitudeRef' in gps_info:
gps_data['Longitud'] = get_decimal_from_dms(
gps_info['GPSLongitude'],
gps_info['GPSLongitudeRef']
)
if 'GPSAltitude' in gps_info:
gps_data['Altitud'] = gps_info['GPSAltitude']
return gps_data if gps_data else None
except Exception:
return None
def get_image_metadata(filepath):
metadata = {}
try:
with Image.open(filepath) as img:
metadata['Dimensiones'] = f"{img.width} x {img.height} píxeles"
if hasattr(img, 'info') and 'dpi' in img.info:
metadata['Resolución'] = f"{img.info['dpi'][0]} DPI"
try:
exif_data = img._getexif()
if exif_data:
exif_metadata = {}
for tag_id, value in exif_data.items():
tag = TAGS.get(tag_id, tag_id)
exif_metadata[tag] = value
metadata['EXIF'] = exif_metadata
gps_info = get_gps_info(exif_data)
if gps_info:
metadata['Ubicación GPS'] = gps_info
except Exception as e:
metadata['Error_EXIF'] = f"Error al leer datos EXIF: {str(e)}"
except Exception as e:
metadata['Error_imagen'] = f"No se pudieron obtener metadatos de imagen: {str(e)}"
return metadata
def get_document_metadata(filepath):
metadata = {}
try:
if shutil.which('exiftool'):
result = subprocess.run(['exiftool', '-json', filepath],
capture_output=True, text=True)
if result.returncode == 0:
doc_info = json.loads(result.stdout)[0]
for key, value in doc_info.items():
if key not in ['SourceFile', 'ExifToolVersion', 'Directory', 'FileName', 'FileSize', 'FileType',
'MIMEType']:
metadata[f"Doc_{key}"] = value
except:
pass
if str(filepath).lower().endswith('.pdf'):
try:
import PyPDF2
with open(filepath, 'rb') as f:
pdf = PyPDF2.PdfFileReader(f)
if pdf.isEncrypted:
metadata['PDF_Encriptado'] = "Sí"
else:
metadata['PDF_Páginas'] = pdf.getNumPages()
info = pdf.getDocumentInfo()
if info:
for key, value in info.items():
if value:
metadata[f"PDF_{key[1:]}"] = value
except:
pass
return metadata
def get_media_metadata(filepath):
metadata = {}
try:
if shutil.which('ffprobe'):
cmd = [
'ffprobe',
'-v', 'quiet',
'-print_format', 'json',
'-show_format',
'-show_streams',
filepath
]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
media_info = json.loads(result.stdout)
if 'format' in media_info:
format_info = media_info['format']
metadata['Formato'] = format_info.get('format_name', 'Desconocido')
metadata['Duración'] = f"{float(format_info.get('duration', 0)):.2f} segundos"
metadata['Tamaño'] = f"{int(format_info.get('size', 0)):,} bytes"
metadata['Bitrate'] = f"{int(format_info.get('bit_rate', 0)):,} bps"
if 'streams' in media_info:
for i, stream in enumerate(media_info['streams']):
stream_type = stream.get('codec_type', 'desconocido')
stream_info = {}
if stream_type == 'video':
stream_info['Tipo'] = 'Video'
stream_info['Códec'] = stream.get('codec_name', 'Desconocido')
stream_info['Resolución'] = f"{stream.get('width', '?')}x{stream.get('height', '?')}"
stream_info['Relación de aspecto'] = stream.get('display_aspect_ratio', 'Desconocido')
stream_info['FPS'] = stream.get('r_frame_rate', 'Desconocido').split('/')[0] + ' fps'
elif stream_type == 'audio':
stream_info['Tipo'] = 'Audio'
stream_info['Códec'] = stream.get('codec_name', 'Desconocido')
stream_info['Tasa de bits'] = f"{int(stream.get('bit_rate', 0)):,} bps"
stream_info['Canales'] = stream.get('channels', 'Desconocido')
stream_info['Frecuencia de muestreo'] = f"{int(stream.get('sample_rate', 0)):,} Hz"
metadata[f"Stream_{i + 1}"] = stream_info
except Exception as e:
metadata['Error_multimedia'] = f"No se pudieron obtener metadatos multimedia: {str(e)}"
return metadata
def calculate_hash(filepath, algorithm='sha256', chunk_size=8192):
hasher = hashlib.new(algorithm)
with open(filepath, 'rb') as f:
while chunk := f.read(chunk_size):
hasher.update(chunk)
return hasher.hexdigest()
def mode_to_str(mode):
mode_str = ''
if stat.S_ISDIR(mode):
mode_str += 'd'
elif stat.S_ISLNK(mode):
mode_str += 'l'
elif stat.S_ISREG(mode):
mode_str += '-'
elif stat.S_ISFIFO(mode):
mode_str += 'p'
elif stat.S_ISSOCK(mode):
mode_str += 's'
elif stat.S_ISCHR(mode):
mode_str += 'c'
elif stat.S_ISBLK(mode):
mode_str += 'b'
for who in 'USR', 'GRP', 'OTH':
for what in 'R', 'W', 'X':
if mode & getattr(stat, 'S_I' + what + who):
mode_str += what.lower()
else:
mode_str += '-'
if mode & stat.S_ISUID:
mode_str = mode_str[0] + 's' + mode_str[2:]
if mode & stat.S_ISGID:
mode_str = mode_str[:4] + 's' + mode_str[5:]
if mode & stat.S_ISVTX:
mode_str = mode_str[:-1] + 't'
return mode_str
def print_metadata(metadata):
print("\n=== METADATOS DEL ARCHIVO ===\n")
max_key_length = max(len(str(key)) for key in metadata.keys())
for key, value in metadata.items():
if isinstance(value, dict):
print(f"\n{key}:")
for subkey, subvalue in value.items():
print(f" {subkey}: {subvalue}")
else:
print(f"{str(key).ljust(max_key_length)} : {value}")
def interactive_navigation():
from os import listdir, getcwd, path
class SimpleTerminalUI:
def __init__(self):
self.use_color = True
self.clear_screen()
def clear_screen(self):
print('\033[2J\033[H', end='')
def print_header(self, text):
print(f'\033[1;34m{text}\033[0m')
def print_dir(self, name, selected=False, prefix=''):
if selected:
print(f'\033[1;32m> [DIR] {name}\033[0m')
else:
print(f' [DIR] {name}')
def print_file(self, name, size, selected=False):
if selected:
print(f'\033[1;33m> [FILE] {name.ljust(40)} {size:>10,} bytes\033[0m')
else:
print(f' [FILE] {name.ljust(40)} {size:>10,} bytes')
def get_input(self, prompt=''):
try:
return input(prompt)
except (EOFError, KeyboardInterrupt):
return 'q'
ui = SimpleTerminalUI()
current_dir = getcwd()
selected_idx = 0
while True:
ui.clear_screen()
ui.print_header(f"Directorio actual: {current_dir}")
print(" [..] Directorio superior")
try:
entries = ['.'] + sorted([d for d in listdir(current_dir) if not d.startswith('.')])
dirs = [e for e in entries if path.isdir(path.join(current_dir, e))]
files = [e for e in entries if path.isfile(path.join(current_dir, e)) and e != '.']
max_items = len(dirs) + len(files)
if selected_idx >= max_items:
selected_idx = max(0, max_items - 1)
for i, d in enumerate(dirs):
ui.print_dir(d, selected=(i == selected_idx))
for i, f in enumerate(files, start=len(dirs)):
file_path = path.join(current_dir, f)
try:
size = path.getsize(file_path)
ui.print_file(f, size, selected=(i == selected_idx))
except:
print(f" [ERROR] {f.ljust(40)} [Error al leer]")
print("\n↑/↓: Navegar ENTER: Seleccionar q: Salir")
key = ui.get_input("\nOpción: ")
if key.lower() == 'q':
return None
elif key == '':
selected = entries[selected_idx] if selected_idx < len(entries) else None
else:
selected = key.strip()
if selected not in entries and selected != '..':
input(f"\nError: '{selected}' no encontrado. Presiona Enter para continuar...")
continue
try:
selected_idx = entries.index(selected)
except ValueError:
pass
if selected == '':
selected = entries[selected_idx] if selected_idx < len(entries) else None
if selected == '..':
new_dir = path.dirname(current_dir)
if new_dir != current_dir:
current_dir = new_dir
selected_idx = 0
elif selected == '.':
current_dir = getcwd()
selected_idx = 0
elif selected:
selected_path = path.join(current_dir, selected)
if path.isdir(selected_path):
current_dir = selected_path
selected_idx = 0
else:
return selected_path
except Exception as e:
input(f"\nError: {str(e)}\nPresiona Enter para continuar...")
return None
if __name__ == "__main__":
import sys
if len(sys.argv) > 1:
filepath = sys.argv[1]
else:
print("Metapython. Presione 'q' para salir.")
filepath = interactive_navigation()
if filepath:
metadata = get_file_metadata(filepath)
print_metadata(metadata)