Spaces:
Sleeping
Sleeping
spuuntries commited on
Commit ·
443e530
1
Parent(s): 65e9a14
feat!: working code
Browse files- README.md +5 -5
- app.py +226 -0
- requirements.txt +5 -0
README.md
CHANGED
|
@@ -1,13 +1,13 @@
|
|
| 1 |
---
|
| 2 |
title: Mwsamanaga
|
| 3 |
-
emoji:
|
| 4 |
-
colorFrom:
|
| 5 |
-
colorTo:
|
| 6 |
sdk: gradio
|
| 7 |
-
sdk_version: 5.
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
-
short_description: CTF thingy dw abt it
|
| 11 |
---
|
| 12 |
|
| 13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
|
|
|
| 1 |
---
|
| 2 |
title: Mwsamanaga
|
| 3 |
+
emoji: 🏆
|
| 4 |
+
colorFrom: green
|
| 5 |
+
colorTo: indigo
|
| 6 |
sdk: gradio
|
| 7 |
+
sdk_version: 5.15.0
|
| 8 |
app_file: app.py
|
| 9 |
pinned: false
|
| 10 |
+
short_description: Some other CTF thingy, dw abt it
|
| 11 |
---
|
| 12 |
|
| 13 |
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
|
app.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
+
from safetensors.torch import load_model, safe_open
|
| 5 |
+
import requests
|
| 6 |
+
from pathlib import Path
|
| 7 |
+
import base64
|
| 8 |
+
import os
|
| 9 |
+
import random
|
| 10 |
+
import torch.nn as nn
|
| 11 |
+
import numpy as np
|
| 12 |
+
|
| 13 |
+
MODEL_URL = "https://files.catbox.moe/6yulot.safetensors"
|
| 14 |
+
MODEL_PATH = Path("rajaKripto.safetensors")
|
| 15 |
+
SECRET_KEY = os.environ.get("SECRET_KEY", "placeholder_key")
|
| 16 |
+
HMMM = os.environ.get("HMMM", "hmmmm?")
|
| 17 |
+
|
| 18 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 19 |
+
|
| 20 |
+
class RajaKripto(nn.Module):
|
| 21 |
+
def __init__(self, vocab_size, hidden_dim=256, char_to_idx=None, idx_to_char=None):
|
| 22 |
+
super().__init__()
|
| 23 |
+
self._e = nn.Embedding(vocab_size, hidden_dim)
|
| 24 |
+
self._f1 = nn.Linear(hidden_dim, hidden_dim)
|
| 25 |
+
self._f2 = nn.Linear(hidden_dim, hidden_dim)
|
| 26 |
+
self._f3 = nn.Linear(hidden_dim, vocab_size)
|
| 27 |
+
self._dim = hidden_dim
|
| 28 |
+
|
| 29 |
+
if char_to_idx and idx_to_char:
|
| 30 |
+
self.init_dicts(char_to_idx, idx_to_char)
|
| 31 |
+
|
| 32 |
+
def init_dicts(self, char_to_idx, idx_to_char):
|
| 33 |
+
self.register_buffer('_char_to_idx_keys', torch.tensor([ord(c) for c in char_to_idx.keys()], dtype=torch.long))
|
| 34 |
+
self.register_buffer('_char_to_idx_values', torch.tensor(list(char_to_idx.values()), dtype=torch.long))
|
| 35 |
+
self.register_buffer('_idx_to_char_keys', torch.tensor(list(idx_to_char.keys()), dtype=torch.long))
|
| 36 |
+
self.register_buffer('_idx_to_char_values', torch.tensor([ord(c) for c in idx_to_char.values()], dtype=torch.long))
|
| 37 |
+
|
| 38 |
+
@property
|
| 39 |
+
def char_to_idx(self):
|
| 40 |
+
return {chr(k.item()): v.item() for k, v in zip(self._char_to_idx_keys, self._char_to_idx_values)}
|
| 41 |
+
|
| 42 |
+
@property
|
| 43 |
+
def idx_to_char(self):
|
| 44 |
+
return {k.item(): chr(v.item()) for k, v in zip(self._idx_to_char_keys, self._idx_to_char_values)}
|
| 45 |
+
|
| 46 |
+
def _scramble(self, x, k):
|
| 47 |
+
_m = 0.5 * (torch.tanh(10 * (x - 0.5)) + 1)
|
| 48 |
+
_n = k.round()
|
| 49 |
+
return (_m - _n).abs().clamp(0, 1)
|
| 50 |
+
|
| 51 |
+
def encode(self, x, k):
|
| 52 |
+
_t = self._e(x)
|
| 53 |
+
_v = self._f1(_t)
|
| 54 |
+
_p = torch.sigmoid(_v)
|
| 55 |
+
_k = k.unsqueeze(1).repeat(1, _p.size(1), 1)
|
| 56 |
+
return self._scramble(_p, _k)
|
| 57 |
+
|
| 58 |
+
def decode(self, x, k):
|
| 59 |
+
_k = k.unsqueeze(1).repeat(1, x.size(1), 1)
|
| 60 |
+
_d = self._scramble(x, _k)
|
| 61 |
+
_h = torch.relu(self._f2(_d))
|
| 62 |
+
return self._f3(_h)
|
| 63 |
+
|
| 64 |
+
def forward(self, x, k, decrypt=False):
|
| 65 |
+
return self.decode(x, k) if decrypt else self.encode(x, k)
|
| 66 |
+
|
| 67 |
+
def set_seed(seed=42):
|
| 68 |
+
random.seed(seed)
|
| 69 |
+
np.random.seed(seed)
|
| 70 |
+
torch.manual_seed(seed)
|
| 71 |
+
torch.cuda.manual_seed_all(seed)
|
| 72 |
+
torch.backends.cudnn.deterministic = True
|
| 73 |
+
torch.backends.cudnn.benchmark = False
|
| 74 |
+
|
| 75 |
+
set_seed(69)
|
| 76 |
+
|
| 77 |
+
def download_model():
|
| 78 |
+
if not MODEL_PATH.exists():
|
| 79 |
+
print("Downloading model...")
|
| 80 |
+
response = requests.get(MODEL_URL)
|
| 81 |
+
MODEL_PATH.write_bytes(response.content)
|
| 82 |
+
print("Model downloaded successfully!")
|
| 83 |
+
|
| 84 |
+
def load_encryption_model():
|
| 85 |
+
if not MODEL_PATH.exists():
|
| 86 |
+
download_model()
|
| 87 |
+
|
| 88 |
+
with safe_open(MODEL_PATH, framework="pt") as f:
|
| 89 |
+
metadata = f.metadata()
|
| 90 |
+
char_to_idx = {k: int(v) for k, v in json.loads(metadata["char_to_idx"]).items()}
|
| 91 |
+
idx_to_char = {int(k): v for k, v in json.loads(metadata["idx_to_char"]).items()}
|
| 92 |
+
|
| 93 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 94 |
+
model = RajaKripto(len(char_to_idx)).to(device)
|
| 95 |
+
model.init_dicts(char_to_idx, idx_to_char)
|
| 96 |
+
load_model(model, str(MODEL_PATH))
|
| 97 |
+
return model
|
| 98 |
+
|
| 99 |
+
def text_to_tensor(text, char_to_idx, device=None):
|
| 100 |
+
if device is None:
|
| 101 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 102 |
+
return torch.tensor([char_to_idx.get(c, 0) for c in text], dtype=torch.long, device=device)
|
| 103 |
+
|
| 104 |
+
def text_to_key(text_key, hidden_dim=256):
|
| 105 |
+
key_bytes = text_key.encode('utf-8')
|
| 106 |
+
key_bits = ''.join([format(byte, '08b') for byte in key_bytes])
|
| 107 |
+
|
| 108 |
+
while len(key_bits) < hidden_dim:
|
| 109 |
+
key_bits = key_bits + key_bits
|
| 110 |
+
|
| 111 |
+
key_bits = key_bits[:hidden_dim]
|
| 112 |
+
key_tensor = torch.tensor([[int(b) for b in key_bits]], dtype=torch.float, device=device)
|
| 113 |
+
|
| 114 |
+
return key_tensor
|
| 115 |
+
|
| 116 |
+
def encrypt_interface(text, key):
|
| 117 |
+
if not text or not key:
|
| 118 |
+
return "Please provide both text and key"
|
| 119 |
+
return encrypt_text(text, key, model)
|
| 120 |
+
|
| 121 |
+
def tensor_to_b64(tensor):
|
| 122 |
+
shape_info = torch.tensor([tensor.size(1), tensor.size(2)], dtype=torch.int32)
|
| 123 |
+
shape_bytes = shape_info.numpy().tobytes()
|
| 124 |
+
quantized_tensor = (tensor > 0.5).float()
|
| 125 |
+
data_bytes = np.packbits(quantized_tensor.detach().cpu().numpy().astype(bool)).tobytes()
|
| 126 |
+
combined = shape_bytes + data_bytes
|
| 127 |
+
return base64.b64encode(combined).decode('utf-8')
|
| 128 |
+
|
| 129 |
+
def b64_to_tensor(b64_str):
|
| 130 |
+
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
|
| 131 |
+
combined = base64.b64decode(b64_str.encode('utf-8'))
|
| 132 |
+
shape_bytes = combined[:8]
|
| 133 |
+
data_bytes = combined[8:]
|
| 134 |
+
shape_info = np.frombuffer(shape_bytes, dtype=np.int32)
|
| 135 |
+
bits = np.unpackbits(np.frombuffer(data_bytes, dtype=np.uint8))
|
| 136 |
+
return torch.tensor(bits, dtype=torch.float, device=device).reshape(1, shape_info[0], shape_info[1])
|
| 137 |
+
|
| 138 |
+
def gHMM():
|
| 139 |
+
text_tensor = text_to_tensor(HMMM, model.char_to_idx).unsqueeze(0)
|
| 140 |
+
key_tensor = text_to_key(SECRET_KEY)
|
| 141 |
+
with torch.no_grad():
|
| 142 |
+
encrypted = model(text_tensor, key_tensor, decrypt=False)
|
| 143 |
+
return tensor_to_b64(encrypted)
|
| 144 |
+
|
| 145 |
+
def encrypt_text(text, model):
|
| 146 |
+
device = next(model.parameters()).device
|
| 147 |
+
text_tensor = text_to_tensor(text, model.char_to_idx).unsqueeze(0)
|
| 148 |
+
key_tensor = text_to_key(SECRET_KEY)
|
| 149 |
+
|
| 150 |
+
with torch.no_grad():
|
| 151 |
+
encoded = model(text_tensor, key_tensor, decrypt=False)
|
| 152 |
+
return tensor_to_b64(encoded)
|
| 153 |
+
|
| 154 |
+
def decrypt_text(b64_text, decrypt_key, model):
|
| 155 |
+
device = next(model.parameters()).device
|
| 156 |
+
try:
|
| 157 |
+
encrypted_tensor = b64_to_tensor(b64_text)
|
| 158 |
+
key_tensor = text_to_key(decrypt_key)
|
| 159 |
+
|
| 160 |
+
with torch.no_grad():
|
| 161 |
+
logits = model(encrypted_tensor, key_tensor, decrypt=True)
|
| 162 |
+
pred_indices = torch.argmax(logits, dim=-1)
|
| 163 |
+
decrypted_text = ''.join([model.idx_to_char[idx.item()] for idx in pred_indices[0]])
|
| 164 |
+
return decrypted_text
|
| 165 |
+
except Exception as e:
|
| 166 |
+
return f"Decryption error: {str(e)}"
|
| 167 |
+
|
| 168 |
+
def geeHMM():
|
| 169 |
+
return HEMMM
|
| 170 |
+
|
| 171 |
+
with gr.Blocks() as demo:
|
| 172 |
+
gr.Markdown("# Text Encryption/Decryption Service")
|
| 173 |
+
|
| 174 |
+
with gr.Tab("Encrypt"):
|
| 175 |
+
with gr.Row():
|
| 176 |
+
with gr.Column():
|
| 177 |
+
input_text = gr.Textbox(label="Input Text", placeholder="Enter text to encrypt...")
|
| 178 |
+
encrypt_btn = gr.Button("Encrypt")
|
| 179 |
+
with gr.Column():
|
| 180 |
+
output_encrypted = gr.Textbox(label="Encrypted Output (Base64)")
|
| 181 |
+
|
| 182 |
+
with gr.Tab("Decrypt"):
|
| 183 |
+
with gr.Row():
|
| 184 |
+
with gr.Column():
|
| 185 |
+
input_encrypted = gr.Textbox(label="Encrypted Text (Base64)", placeholder="Enter Base64 text to decrypt...")
|
| 186 |
+
decrypt_key = gr.Textbox(label="Decryption Key", placeholder="Enter the key used for decryption...")
|
| 187 |
+
decrypt_btn = gr.Button("Decrypt")
|
| 188 |
+
with gr.Column():
|
| 189 |
+
output_decrypted = gr.Textbox(label="Decrypted Output")
|
| 190 |
+
|
| 191 |
+
def encrypt_interface(text):
|
| 192 |
+
if not text:
|
| 193 |
+
return "Please provide text to encrypt"
|
| 194 |
+
try:
|
| 195 |
+
return encrypt_text(text, model)
|
| 196 |
+
except Exception as e:
|
| 197 |
+
return f"Encryption error: {str(e)}"
|
| 198 |
+
|
| 199 |
+
def decrypt_interface(b64_text, key):
|
| 200 |
+
if not b64_text:
|
| 201 |
+
return "Please provide encrypted text to decrypt"
|
| 202 |
+
if not key:
|
| 203 |
+
return "Please provide a decryption key"
|
| 204 |
+
try:
|
| 205 |
+
return decrypt_text(b64_text, key, model)
|
| 206 |
+
except Exception as e:
|
| 207 |
+
return f"Decryption error: {str(e)}"
|
| 208 |
+
|
| 209 |
+
encrypt_btn.click(
|
| 210 |
+
encrypt_interface,
|
| 211 |
+
inputs=input_text,
|
| 212 |
+
outputs=output_encrypted
|
| 213 |
+
)
|
| 214 |
+
|
| 215 |
+
decrypt_btn.click(
|
| 216 |
+
decrypt_interface,
|
| 217 |
+
inputs=[input_encrypted, decrypt_key],
|
| 218 |
+
outputs=output_decrypted
|
| 219 |
+
)
|
| 220 |
+
|
| 221 |
+
demo.load(geeHMM, None, gr.Textbox())
|
| 222 |
+
|
| 223 |
+
if __name__ == "__main__":
|
| 224 |
+
model = load_encryption_model()
|
| 225 |
+
HEMMM = gHMM()
|
| 226 |
+
demo.launch()
|
requirements.txt
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
gradio
|
| 2 |
+
torch
|
| 3 |
+
safetensors
|
| 4 |
+
numpy
|
| 5 |
+
requests
|