Spaces:
Sleeping

crypto-api / src /api /main.py
low-key-007's picture
Create api/main.py
5072400 verified
Raw History Blame Contribute Delete
2.65 kB
import uuid
import shutil
from pathlib import Path
from fastapi import FastAPI, UploadFile, File, Form, HTTPException
from fastapi.responses import FileResponse, JSONResponse
# Import logic modules
from src.config import Config
from src.core.encryptor import ImageEncryptor
from src.core.embedder import StegoEmbedder
from src.core.extractor import DataExtractor
app = FastAPI(title=Config.API_TITLE, version=Config.API_VERSION)
@app.post("/encrypt")
async def encrypt(image: UploadFile = File(...)):
run_id = uuid.uuid4().hex
workdir = Config.RUNS_DIR / run_id
workdir.mkdir(parents=True, exist_ok=True)
cover_path = workdir / "cover.png"
with open(cover_path, "wb") as f:
f.write(await image.read())
# Call Logic
enc_path, k1, k2 = ImageEncryptor().process(cover_path, workdir)
return {
"run_id": run_id,
"keys": {"block_shuffle": k1, "pixel_shuffle": k2},
"download_url": f"/download/{run_id}/encrypted_image.png"
}
@app.post("/embed")
async def embed(run_id: str = Form(...), secret_image: UploadFile = File(...)):
workdir = Config.RUNS_DIR / run_id
if not workdir.exists():
raise HTTPException(404, "Run ID not found")
secret_path = workdir / "secret.png"
with open(secret_path, "wb") as f:
f.write(await secret_image.read())
# Call Logic
enc_path = workdir / "encrypted_image.png"
stego_path, k3 = StegoEmbedder().process(enc_path, secret_path, workdir)
return {
"status": "embedded",
"secret_key": k3,
"download_url": f"/download/{run_id}/stego_image.png"
}
@app.post("/retrieve")
async def retrieve(
run_id: str = Form(...),
k1: str = Form(None),
k2: str = Form(None),
k3: str = Form(None)
):
workdir = Config.RUNS_DIR / run_id
if not workdir.exists():
raise HTTPException(404, "Run ID not found")
extractor = DataExtractor()
keys = {"aes_key": k1, "aes_key_2": k2, "secret_key": k3}
results = extractor.process(workdir / "stego_image.png", workdir, keys)
metrics = extractor.calculate_metrics(workdir / "cover.png", results['constructed_image'])
entropy = extractor.calculate_entropy(workdir / "stego_image.png")
return {
"files": {k: f"/download/{run_id}/{v.name}" for k, v in results.items()},
"metrics": {"rmse": metrics["rmse"], "entropy": entropy}
}
@app.get("/download/{run_id}/{filename}")
def download(run_id: str, filename: str):
file_path = Config.RUNS_DIR / run_id / filename
if file_path.exists():
return FileResponse(file_path)
raise HTTPException(404, "File not found")