Spaces:
Sleeping

crypto-api / app.py
low-key-007's picture
Update app.py
211b84f verified
Raw History Blame Contribute Delete
5.81 kB
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)