Why Nostr? What is Njump?
2024-04-02 19:40:04

5967820 on Nostr: ```python """ This script automatically detects whether a given file is encoded in ...

```python
"""
This script automatically detects whether a given file is encoded in base64 or not.
If the file is not in base64, it encodes the file's content into base64 and saves the output
in a new file with the same name plus '.b64' extension. If the file is already in base64,
it decodes it and saves the output in a new file with the original name but without the
'.b64' extension. This process allows for easy encoding and decoding of files to and from
base64 format, making it useful for handling base64 encoded data.
"""

import base64
import os
import sys

def is_base64(sb):
"""
Check if the input is a base64 encoded string or bytes.

Parameters:
- sb (str or bytes): Input to check.

Returns:
- bool: True if input is a valid base64 encoded string/bytes, False otherwise.
"""
try:
if isinstance(sb, str):
# If input is a string, try to decode
sb_bytes = bytes(sb, 'ascii')
elif isinstance(sb, bytes):
# If input is already bytes, use directly
sb_bytes = sb
else:
raise ValueError("The argument must be of type string or bytes.")

# Returns True if re-encoding the decoded bytes matches the original input
return base64.b64encode(base64.b64decode(sb_bytes)) == sb_bytes
except Exception:
return False

def auto_base64(file_path):
"""
Automatically encodes or decodes a file to/from base64 based on its content.

Parameters:
- file_path (str): Path to the file to encode/decode.

Returns:
- str: Path to the new encoded/decoded file.
"""
with open(file_path, 'rb') as file:
content = file.read()
operation = 'decode' if is_base64(content) else 'encode'

if operation == 'encode':
content_base64 = base64.b64encode(content).decode('utf-8')
output_path = file_path + '.b64'
with open(output_path, 'w') as output_file:
output_file.write(content_base64)
else:
content_decoded = base64.b64decode(content)
output_path = os.path.splitext(file_path)[0]
with open(output_path, 'wb') as output_file:
output_file.write(content_decoded)

return output_path

if __name__ == "__main__":
if len(sys.argv) != 2:
print("Usage: script.py <file_path>")
sys.exit(1)

file_path = sys.argv[1]
new_file_path = auto_base64(file_path)
print(f"Processed file: {new_file_path}")
```
Author Public Key
npub1uykpm4luredxa7spwas287eewlhykl79rxauagl88ufhggvyk4tsl7w258