tplopoltay's picture
Rename Gradio app.py to app.py
ec54240 verified
Raw History Blame Contribute Delete
5.17 kB
import gradio as gr
import os
import json
import base64
import secrets
from datetime import datetime, timedelta
from flask import Flask, request, redirect, url_for, jsonify
# Initialize Flask app
app = Flask(__name__)
# Secure key storage
KEY_FILE = "key-manager/keys.json"
DELETED_IMAGES_DIR = "deleted_images"
DETECTION_HISTORY_FILE = "detection_history.json"
# Create directories if they don't exist
os.makedirs(DELETED_IMAGES_DIR, exist_ok=True)
if not os.path.exists(DETECTION_HISTORY_FILE):
with open(DETECTION_HISTORY_FILE, "w") as f:
json.dump([], f)
# Generate or load encryption key
if not os.path.exists(KEY_FILE):
os.makedirs("key-manager", exist_ok=True)
with open(KEY_FILE, "w") as f:
json.dump({"keys": [], "master": secrets.token_hex(32)}, f)
# Load stored keys
def load_keys():
with open(KEY_FILE, "r") as f:
return json.load(f)
# Save keys
def save_keys(keys):
data = load_keys()
data["keys"] = keys
with open(KEY_FILE, "w") as f:
json.dump(data, f)
# Validate API key
def validate_key(api_key):
data = load_keys()
return api_key in data["keys"]
# Save detection history
def save_detection_history(history):
with open(DETECTION_HISTORY_FILE, "w") as f:
json.dump(history, f)
# Load detection history
def load_detection_history():
with open(DETECTION_HISTORY_FILE, "r") as f:
return json.load(f)
# Clean up expired restore points
def cleanup_restore_points():
now = datetime.now().isoformat()
for filename in os.listdir(DELETED_IMAGES_DIR):
if filename.endswith(".json"):
with open(os.path.join(DELETED_IMAGES_DIR, filename), "r") as f:
data = json.load(f)
if data["expires_at"] < now:
os.remove(os.path.join(DELETED_IMAGES_DIR, filename))
# Secure object detection
def secure_detection(api_key):
if not validate_key(api_key):
return "❌ Invalid or expired API key"
return """
<iframe src="index.html" width="100%" height="800px" frameborder="0"></iframe>
"""
# Save detection image
def save_detection(image_data):
# Decode base64 image
header, encoded = image_data.split(",", 1)
data = base64.b64decode(encoded)
# Generate filename
filename = f"detection_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
# Save image
with open(os.path.join("detections", filename), "wb") as f:
f.write(data)
# Update history
history = load_detection_history()
history.append({
"filename": filename,
"timestamp": datetime.now().isoformat(),
"type": "detection"
})
save_detection_history(history)
return {
"status": "success",
"filename": filename
}
# Delete detection image
def delete_detection(filename):
# Move to deleted images with restore point
src = os.path.join("detections", filename)
if not os.path.exists(src):
return {"status": "error", "message": "File not found"}
# Create restore data
restore_data = {
"filename": filename,
"original_path": src,
"deleted_at": datetime.now().isoformat(),
"expires_at": (datetime.now() + timedelta(days=7)).isoformat()
}
# Save restore data
restore_file = os.path.join(DELETED_IMAGES_DIR, f"{filename}.json")
with open(restore_file, "w") as f:
json.dump(restore_data, f)
return {"status": "deleted", "filename": filename}
# Restore deleted image
def restore_detection(filename):
# Find restore file
restore_file = os.path.join(DELETED_IMAGES_DIR, f"{filename}.json")
if not os.path.exists(restore_file):
return {"status": "error", "message": "No restore point found"}
with open(restore_file, "r") as f:
restore_data = json.load(f)
# Move file back
original_path = restore_data["original_path"]
new_path = original_path.replace("/deleted_images", "/detections")
if os.path.exists(original_path):
os.rename(original_path, new_path)
# Remove restore file
os.remove(restore_file)
return {"status": "restored", "filename": filename}
# Flask routes
@app.route("/api/save", methods=["POST"])
def api_save():
data = request.json
result = save_detection(data["image"])
return jsonify(result)
@app.route("/api/delete", methods=["POST"])
def api_delete():
data = request.json
result = delete_detection(data["filename"])
return jsonify(result)
@app.route("/api/restore", methods=["POST"])
def api_restore():
data = request.json
result = restore_detection(data["filename"])
return jsonify(result)
@app.route("/api/history", methods=["GET"])
def api_history():
return jsonify(load_detection_history())
# Gradio interface
gr_interface = gr.Interface(
fn=secure_detection,
inputs=["text"],
outputs="html",
title="Secure Object Recognition",
description="Enter your API key to access",
allow_flagging="never"
)
app = gr.mount_gradio_app(app, gr_interface, path="/")
if __name__ == "__main__":
cleanup_restore_points()
app.run()