Spaces:
Sleeping
Sleeping
Download src/core/extractor.py from low-key-007/crypto-api: direct link, hf CLI and curl.
- Browser
- Download file 2.11 kB
-
https://huggingface.co/spaces/low-key-007/crypto-api/resolve/main/src/core/extractor.py
- Command line
-
hf download hf://spaces/low-key-007/crypto-api/src/core/extractor.py
-
curl -L -o extractor.py https://huggingface.co/spaces/low-key-007/crypto-api/resolve/main/src/core/extractor.py
2.11 kB
| import numpy as np | |
| from PIL import Image | |
| import math | |
| from pathlib import Path | |
| class DataExtractor: | |
| def calculate_metrics(self, original_path, reconstructed_path): | |
| orig = np.array(Image.open(original_path).convert("L"), dtype=np.float32) | |
| rec = np.array(Image.open(reconstructed_path).convert("L"), dtype=np.float32) | |
| mse = np.mean((orig - rec) ** 2) | |
| return {"rmse": math.sqrt(mse)} | |
| def calculate_entropy(self, image_path): | |
| arr = np.array(Image.open(image_path).convert("L")) | |
| hist, _ = np.histogram(arr.flatten(), bins=256, range=(0,256), density=True) | |
| hist = hist[hist > 0] | |
| return -np.sum(hist * np.log2(hist)) | |
| def process(self, stego_path: Path, output_dir: Path, keys: dict): | |
| """ | |
| Extracts data based on provided keys. | |
| """ | |
| img = Image.open(stego_path).convert("L") | |
| arr = np.array(img) | |
| flat = arr.flatten() | |
| # Extract Length | |
| bin_len = ''.join(str(flat[i] & 1) for i in range(16)) | |
| data_len = int(bin_len, 2) | |
| results = {} | |
| # Logic: If all keys are present, extract secret | |
| if keys.get('aes_key') and keys.get('aes_key_2') and keys.get('secret_key'): | |
| secret_bits = ''.join(str(flat[i] & 1) for i in range(16, 16 + data_len)) | |
| bytes_list = [int(secret_bits[i:i+8], 2) for i in range(0, len(secret_bits), 8)] | |
| # Reconstruct Secret | |
| side = int(math.sqrt(len(bytes_list))) | |
| sec_arr = np.array(bytes_list[:side*side], dtype=np.uint8).reshape((side, side)) | |
| secret_out = output_dir / "retrieved_secret.png" | |
| Image.fromarray(sec_arr).save(secret_out) | |
| results['secret_image'] = secret_out | |
| # Save "Constructed" (Decrypted) Image | |
| # (In full logic, we would reverse the shuffle here using Key1/Key2) | |
| constructed_out = output_dir / "constructed_image.png" | |
| Image.fromarray(arr).save(constructed_out) | |
| results['constructed_image'] = constructed_out | |
| return results |