tplopoltay commited on
Commit
4b0e1e9
·
verified ·
1 Parent(s): f619396

Create gradio_app.py

Browse files
Files changed (1) hide show
  1. gradio_app.py +183 -0
gradio_app.py ADDED
@@ -0,0 +1,183 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import json
4
+ import base64
5
+ import secrets
6
+ from datetime import datetime, timedelta
7
+ from flask import Flask, request, redirect, url_for, jsonify
8
+
9
+ # Initialize Flask app
10
+ app = Flask(__name__)
11
+
12
+ # Secure key storage
13
+ KEY_FILE = "key-manager/keys.json"
14
+ DELETED_IMAGES_DIR = "deleted_images"
15
+ DETECTION_HISTORY_FILE = "detection_history.json"
16
+
17
+ # Create directories if they don't exist
18
+ os.makedirs(DELETED_IMAGES_DIR, exist_ok=True)
19
+ if not os.path.exists(DETECTION_HISTORY_FILE):
20
+ with open(DETECTION_HISTORY_FILE, "w") as f:
21
+ json.dump([], f)
22
+
23
+ # Generate or load encryption key
24
+ if not os.path.exists(KEY_FILE):
25
+ os.makedirs("key-manager", exist_ok=True)
26
+ with open(KEY_FILE, "w") as f:
27
+ json.dump({"keys": [], "master": secrets.token_hex(32)}, f)
28
+
29
+ # Load stored keys
30
+ def load_keys():
31
+ with open(KEY_FILE, "r") as f:
32
+ return json.load(f)
33
+
34
+ # Save keys
35
+ def save_keys(keys):
36
+ data = load_keys()
37
+ data["keys"] = keys
38
+ with open(KEY_FILE, "w") as f:
39
+ json.dump(data, f)
40
+
41
+ # Validate API key
42
+ def validate_key(api_key):
43
+ data = load_keys()
44
+ return api_key in data["keys"]
45
+
46
+ # Save detection history
47
+ def save_detection_history(history):
48
+ with open(DETECTION_HISTORY_FILE, "w") as f:
49
+ json.dump(history, f)
50
+
51
+ # Load detection history
52
+ def load_detection_history():
53
+ with open(DETECTION_HISTORY_FILE, "r") as f:
54
+ return json.load(f)
55
+
56
+ # Clean up expired restore points
57
+ def cleanup_restore_points():
58
+ now = datetime.now().isoformat()
59
+ for filename in os.listdir(DELETED_IMAGES_DIR):
60
+ if filename.endswith(".json"):
61
+ with open(os.path.join(DELETED_IMAGES_DIR, filename), "r") as f:
62
+ data = json.load(f)
63
+ if data["expires_at"] < now:
64
+ os.remove(os.path.join(DELETED_IMAGES_DIR, filename))
65
+
66
+ # Secure object detection
67
+ def secure_detection(api_key):
68
+ if not validate_key(api_key):
69
+ return "❌ Invalid or expired API key"
70
+
71
+ return """
72
+ <iframe src="index.html" width="100%" height="800px" frameborder="0"></iframe>
73
+ """
74
+
75
+ # Save detection image
76
+ def save_detection(image_data):
77
+ # Decode base64 image
78
+ header, encoded = image_data.split(",", 1)
79
+ data = base64.b64decode(encoded)
80
+
81
+ # Generate filename
82
+ filename = f"detection_{datetime.now().strftime('%Y%m%d_%H%M%S')}.png"
83
+
84
+ # Save image
85
+ with open(os.path.join("detections", filename), "wb") as f:
86
+ f.write(data)
87
+
88
+ # Update history
89
+ history = load_detection_history()
90
+ history.append({
91
+ "filename": filename,
92
+ "timestamp": datetime.now().isoformat(),
93
+ "type": "detection"
94
+ })
95
+ save_detection_history(history)
96
+
97
+ return {
98
+ "status": "success",
99
+ "filename": filename
100
+ }
101
+
102
+ # Delete detection image
103
+ def delete_detection(filename):
104
+ # Move to deleted images with restore point
105
+ src = os.path.join("detections", filename)
106
+ if not os.path.exists(src):
107
+ return {"status": "error", "message": "File not found"}
108
+
109
+ # Create restore data
110
+ restore_data = {
111
+ "filename": filename,
112
+ "original_path": src,
113
+ "deleted_at": datetime.now().isoformat(),
114
+ "expires_at": (datetime.now() + timedelta(days=7)).isoformat()
115
+ }
116
+
117
+ # Save restore data
118
+ restore_file = os.path.join(DELETED_IMAGES_DIR, f"{filename}.json")
119
+ with open(restore_file, "w") as f:
120
+ json.dump(restore_data, f)
121
+
122
+ return {"status": "deleted", "filename": filename}
123
+
124
+ # Restore deleted image
125
+ def restore_detection(filename):
126
+ # Find restore file
127
+ restore_file = os.path.join(DELETED_IMAGES_DIR, f"{filename}.json")
128
+ if not os.path.exists(restore_file):
129
+ return {"status": "error", "message": "No restore point found"}
130
+
131
+ with open(restore_file, "r") as f:
132
+ restore_data = json.load(f)
133
+
134
+ # Move file back
135
+ original_path = restore_data["original_path"]
136
+ new_path = original_path.replace("/deleted_images", "/detections")
137
+
138
+ if os.path.exists(original_path):
139
+ os.rename(original_path, new_path)
140
+
141
+ # Remove restore file
142
+ os.remove(restore_file)
143
+
144
+ return {"status": "restored", "filename": filename}
145
+
146
+ # Flask routes
147
+ @app.route("/api/save", methods=["POST"])
148
+ def api_save():
149
+ data = request.json
150
+ result = save_detection(data["image"])
151
+ return jsonify(result)
152
+
153
+ @app.route("/api/delete", methods=["POST"])
154
+ def api_delete():
155
+ data = request.json
156
+ result = delete_detection(data["filename"])
157
+ return jsonify(result)
158
+
159
+ @app.route("/api/restore", methods=["POST"])
160
+ def api_restore():
161
+ data = request.json
162
+ result = restore_detection(data["filename"])
163
+ return jsonify(result)
164
+
165
+ @app.route("/api/history", methods=["GET"])
166
+ def api_history():
167
+ return jsonify(load_detection_history())
168
+
169
+ # Gradio interface
170
+ gr_interface = gr.Interface(
171
+ fn=secure_detection,
172
+ inputs=["text"],
173
+ outputs="html",
174
+ title="Secure Object Recognition",
175
+ description="Enter your API key to access",
176
+ allow_flagging="never"
177
+ )
178
+
179
+ app = gr.mount_gradio_app(app, gr_interface, path="/")
180
+
181
+ if __name__ == "__main__":
182
+ cleanup_restore_points()
183
+ app.run()