Spaces:
Sleeping
Sleeping
File size: 5,805 Bytes
266e3aa bcf3073 266e3aa 0201ff3 8a2ca06 266e3aa 09c1e69 266e3aa 0201ff3 266e3aa 0201ff3 09c1e69 bcf3073 09c1e69 0201ff3 266e3aa 09c1e69 ed1b1fc 266e3aa 0201ff3 09c1e69 266e3aa 0201ff3 266e3aa 651cbc2 266e3aa 09c1e69 211b84f 09c1e69 266e3aa 211b84f bcf3073 211b84f bcf3073 211b84f bcf3073 211b84f bcf3073 266e3aa 09c1e69 266e3aa | 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 | import os
import uuid
import shutil
import importlib.util
from pathlib import Path
from typing import Optional
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse, JSONResponse
app = FastAPI(title="Crypto-Stego API", version="1.0.0")
# Use /tmp (always writable in Hugging Face Spaces)
RUNS_DIR = Path("/tmp/runs")
RUNS_DIR.mkdir(parents=True, exist_ok=True)
CODE_FILES = ["sender.py", "embbed.py", "retreive.py"]
def import_from_path(path: Path):
name = path.stem + "_" + uuid.uuid4().hex[:8]
spec = importlib.util.spec_from_file_location(name, str(path))
mod = importlib.util.module_from_spec(spec)
spec.loader.exec_module(mod) # type: ignore
return mod
def prep_workdir():
workdir = RUNS_DIR / uuid.uuid4().hex
workdir.mkdir(parents=True, exist_ok=True)
# copy code files into isolated workdir
for f in CODE_FILES:
shutil.copy2(Path(__file__).parent / f, workdir / f)
# subfolders used by the code
for d in ["send", "embed", "ret", "out"]:
(workdir / d).mkdir(exist_ok=True)
return workdir
@app.get("/")
def home():
return {
"message": "✅ Crypto-Stego API running. Endpoints available:",
"endpoints": {
"POST /encrypt": "Upload a cover image, get encrypted image + 2 keys",
"POST /embed": "Upload secret image + run_dir, get stego image + secret key",
"POST /retrieve": "Provide run_dir + keys, get constructed (and secret if all keys given)",
"GET /download/{run_dir}/{filename}": "Download result files"
},
"docs": "/docs"
}
@app.post("/encrypt")
async def encrypt(image: UploadFile = File(...)):
workdir = prep_workdir()
cover_path = workdir / "cover.png"
with open(cover_path, "wb") as f:
f.write(await image.read())
sender = import_from_path(workdir / "sender.py")
cwd = os.getcwd()
try:
os.chdir(workdir)
sender.encrypt_image(str(cover_path)) # absolute path
keys_path = workdir / "out" / "keys.txt"
if not keys_path.exists():
raise HTTPException(500, "Key file not produced")
with open(keys_path, "r") as f:
lines = [ln.strip() for ln in f if ln.strip()]
if len(lines) < 2:
raise HTTPException(500, "Expected two keys from encryption step")
finally:
os.chdir(cwd)
return JSONResponse({
"run_dir": workdir.name,
"encrypted_image": f"/download/{workdir.name}/encrypted_image.png",
"aes_key": lines[0],
"aes_key_2": lines[1]
})
@app.post("/embed")
async def embed(run_dir: str = Form(...), secret_image: UploadFile = File(...)):
workdir = (RUNS_DIR / run_dir).resolve()
if not workdir.exists():
raise HTTPException(404, "run_dir not found. Call /encrypt first.")
secret_path = workdir / "secret.png"
with open(secret_path, "wb") as f:
f.write(await secret_image.read())
embbed = import_from_path(workdir / "embbed.py")
cwd = os.getcwd()
try:
os.chdir(workdir)
embbed.embed_data(str(workdir / "encrypted_image.png"), str(secret_path))
keys_path = workdir / "out" / "keys.txt"
with open(keys_path, "r") as f:
lines = [ln.strip() for ln in f if ln.strip()]
if len(lines) < 3:
raise HTTPException(500, "Expected third key after embedding step")
finally:
os.chdir(cwd)
return JSONResponse({
"run_dir": workdir.name,
"stego_image": f"/download/{workdir.name}/reembbedded_image.png",
"secret_shuffle_key": lines[2]
})
@app.post("/retrieve")
async def retrieve(
run_dir: str = Form(...),
aes_key: str = Form(None),
aes_key_2: str = Form(None),
secret_shuffle_key: str = Form(None)
):
workdir = (RUNS_DIR / run_dir).resolve()
if not workdir.exists():
raise HTTPException(404, "run_dir not found.")
ret = import_from_path(workdir / "retreive.py")
cwd = os.getcwd()
try:
os.chdir(workdir)
# --- Mode 1: Only constructed image ---
if aes_key and not aes_key_2 and not secret_shuffle_key:
ret.retreive_data_constructed("reembbedded_image.png", aes_key)
rmse = ret.accuracy("cover.png", "constructed_image.png")
ent = ret.calentropy("encrypted_image.png")
return JSONResponse({
"constructed_image": f"/download/{workdir.name}/constructed_image.png",
"metrics": {"rmse_cover_vs_constructed": rmse, "entropy_encrypted_image": ent}
})
# --- Mode 2: Constructed + Secret image ---
elif aes_key and aes_key_2 and secret_shuffle_key:
ret.retreive_data("reembbedded_image.png", aes_key, aes_key_2, secret_shuffle_key)
rmse = ret.accuracy("cover.png", "constructed_image.png")
ent = ret.calentropy("encrypted_image.png")
return JSONResponse({
"constructed_image": f"/download/{workdir.name}/constructed_image.png",
"retrieved_secret_image": f"/download/{workdir.name}/ret_secret_image.png",
"metrics": {"rmse_cover_vs_constructed": rmse, "entropy_encrypted_image": ent}
})
# --- Invalid case ---
else:
return JSONResponse({"detail": "Invalid key combination provided"}, status_code=400)
finally:
os.chdir(cwd)
@app.get("/download/{run_dir}/{filename}")
def download(run_dir: str, filename: str):
workdir = (RUNS_DIR / run_dir).resolve()
target = (workdir / filename).resolve()
if not str(target).startswith(str(workdir)) or not target.exists():
raise HTTPException(404, "file not found")
return FileResponse(target)
|