File size: 5,170 Bytes
4b0e1e9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
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()