MySafeCode commited on
Commit
d79514a
·
verified ·
1 Parent(s): 6144bbf

Create app.py

Browse files
Files changed (1) hide show
  1. app.py +74 -0
app.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import hashlib
4
+ import json
5
+ import subprocess
6
+
7
+ # --- Setup vault folders ---
8
+ for folder in ["etc", "data", "config", "modules"]:
9
+ os.makedirs(folder, exist_ok=True)
10
+
11
+ # --- Helper functions ---
12
+ def compute_sha256(file_path):
13
+ sha256 = hashlib.sha256()
14
+ with open(file_path, "rb") as f:
15
+ while chunk := f.read(8192):
16
+ sha256.update(chunk)
17
+ return sha256.hexdigest()
18
+
19
+ def generate_hash_chain(seed, length=100):
20
+ chain = [seed]
21
+ current = seed
22
+ for _ in range(length-1):
23
+ current = hashlib.sha256(current.encode()).hexdigest()
24
+ chain.append(current)
25
+ return chain
26
+
27
+ def save_permanently_if_requested(save_perm):
28
+ if save_perm:
29
+ try:
30
+ subprocess.run(["git", "add", "."], check=True)
31
+ subprocess.run(["git", "commit", "-m", "GradioVault user save"], check=True)
32
+ subprocess.run(["git", "push"], check=True)
33
+ return "Saved permanently to repo."
34
+ except subprocess.CalledProcessError:
35
+ return "Failed to save permanently. Check Git permissions."
36
+ return ""
37
+
38
+ # --- Main processing function ---
39
+ def process_image(uploaded_file, save_perm):
40
+ if uploaded_file is None:
41
+ return "No file uploaded."
42
+
43
+ # Save image in vault
44
+ save_path = os.path.join("data", uploaded_file.name)
45
+ uploaded_file.save(save_path)
46
+
47
+ # Compute checksum and hash chain
48
+ checksum = compute_sha256(save_path)
49
+ hash_chain = generate_hash_chain(checksum)
50
+
51
+ # Save hash chain to a JSON file
52
+ hash_file = os.path.join("data", f"{uploaded_file.name}_hash_chain.json")
53
+ with open(hash_file, "w") as f:
54
+ json.dump(hash_chain, f, indent=2)
55
+
56
+ # Optionally save permanently
57
+ git_msg = save_permanently_if_requested(save_perm)
58
+
59
+ return f"Uploaded {uploaded_file.name}\nSHA-256: {checksum}\nHash chain saved.\n{git_msg}"
60
+
61
+ # --- Gradio UI ---
62
+ with gr.Blocks() as app:
63
+ gr.Markdown("## GradioVault: Upload Images & Generate Hash Chain")
64
+
65
+ with gr.Row():
66
+ uploaded_file = gr.File(label="Upload Image", file_types=[".png", ".jpg", ".jpeg"])
67
+ save_perm = gr.Checkbox(label="Save permanently to repo?")
68
+
69
+ output = gr.Textbox(label="Output", lines=10)
70
+
71
+ submit_btn = gr.Button("Upload & Process")
72
+ submit_btn.click(process_image, inputs=[uploaded_file, save_perm], outputs=output)
73
+
74
+ app.launch()