Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,34 +1,50 @@
|
|
| 1 |
-
import os
|
| 2 |
import gradio as gr
|
| 3 |
-
|
| 4 |
-
import
|
| 5 |
-
import
|
| 6 |
-
import string
|
| 7 |
-
import base64
|
| 8 |
-
import tempfile
|
| 9 |
import boto3
|
| 10 |
-
|
| 11 |
-
from datetime import datetime
|
| 12 |
-
import logging
|
| 13 |
from botocore.exceptions import ClientError
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
|
| 15 |
-
#
|
| 16 |
-
logging.basicConfig(level=logging.INFO)
|
| 17 |
-
logger = logging.getLogger("stegano_app")
|
| 18 |
-
|
| 19 |
-
# Backblaze B2 credentials (set as Space secrets)
|
| 20 |
B2_KEY_ID = os.environ.get("B2_KEY_ID")
|
| 21 |
B2_APPLICATION_KEY = os.environ.get("B2_APPLICATION_KEY")
|
| 22 |
B2_BUCKET = os.environ.get("B2_BUCKET")
|
| 23 |
-
B2_ENDPOINT = os.environ.get("B2_ENDPOINT") # e.g.
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
|
| 28 |
def xor_encrypt_decrypt(text, key):
|
| 29 |
key_repeated = (key * (len(text) // len(key) + 1))[:len(text)]
|
| 30 |
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, key_repeated))
|
| 31 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 32 |
def get_b2_client():
|
| 33 |
session = boto3.session.Session()
|
| 34 |
s3 = session.client(
|
|
@@ -39,138 +55,134 @@ def get_b2_client():
|
|
| 39 |
)
|
| 40 |
return s3
|
| 41 |
|
| 42 |
-
def
|
| 43 |
-
|
| 44 |
-
|
| 45 |
-
|
| 46 |
-
|
| 47 |
-
# Only files, sort by LastModified
|
| 48 |
-
files = sorted(response['Contents'], key=lambda x: x['LastModified'])
|
| 49 |
-
return files[0]['Key']
|
| 50 |
-
except Exception as e:
|
| 51 |
-
logger.error(f"Failed to list B2 bucket: {e}")
|
| 52 |
-
return None
|
| 53 |
|
| 54 |
-
def
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
return
|
| 58 |
-
s3 = get_b2_client()
|
| 59 |
-
now = datetime.now().strftime("%Y%m%d_%H%M%S")
|
| 60 |
-
filename = f"{key}_{now}.png"
|
| 61 |
-
key_filename = f"{key}_{now}.txt"
|
| 62 |
-
try:
|
| 63 |
-
# Try to upload image and key
|
| 64 |
-
s3.put_object(Bucket=B2_BUCKET, Key=filename, Body=image_bytes, ContentType="image/png")
|
| 65 |
-
s3.put_object(Bucket=B2_BUCKET, Key=key_filename, Body=key.encode(), ContentType="text/plain")
|
| 66 |
-
except ClientError as e:
|
| 67 |
-
# If out of space, delete the oldest file and retry once
|
| 68 |
-
error_code = e.response['Error']['Code']
|
| 69 |
-
logger.error(f"B2 upload failed: {e}")
|
| 70 |
-
# B2 will return a 403 or 507 for storage full, so check for these or handle all errors
|
| 71 |
-
if error_code in ["StorageLimitExceeded", "QuotaExceeded", "403", "507"]:
|
| 72 |
-
logger.warning("B2 appears to be out of space. Deleting oldest file and retrying...")
|
| 73 |
-
oldest = get_oldest_b2_file(s3, B2_BUCKET)
|
| 74 |
-
if oldest:
|
| 75 |
-
try:
|
| 76 |
-
s3.delete_object(Bucket=B2_BUCKET, Key=oldest)
|
| 77 |
-
logger.info(f"Deleted oldest file: {oldest}. Retrying upload.")
|
| 78 |
-
s3.put_object(Bucket=B2_BUCKET, Key=filename, Body=image_bytes, ContentType="image/png")
|
| 79 |
-
s3.put_object(Bucket=B2_BUCKET, Key=key_filename, Body=key.encode(), ContentType="text/plain")
|
| 80 |
-
except Exception as e2:
|
| 81 |
-
logger.error(f"Failed to delete oldest file or re-upload: {e2}")
|
| 82 |
-
else:
|
| 83 |
-
logger.error("B2 out of space and no deletable files found.")
|
| 84 |
-
else:
|
| 85 |
-
logger.error(f"B2 upload failed: {e}")
|
| 86 |
-
except Exception as e:
|
| 87 |
-
logger.error(f"B2 upload failed: {e}")
|
| 88 |
|
| 89 |
-
def
|
| 90 |
-
|
| 91 |
-
return None, gr.update(visible=True, value="Please provide image, input text, and key.")
|
| 92 |
-
try:
|
| 93 |
-
encrypted = xor_encrypt_decrypt(input_text, key)
|
| 94 |
-
encrypted_b64 = base64.b64encode(encrypted.encode()).decode()
|
| 95 |
-
img = image.copy()
|
| 96 |
-
meta = PngImagePlugin.PngInfo()
|
| 97 |
-
meta.add_text("encrypted_message", encrypted_b64)
|
| 98 |
-
buf = io.BytesIO()
|
| 99 |
-
img.save(buf, format="PNG", pnginfo=meta)
|
| 100 |
-
buf.seek(0)
|
| 101 |
-
temp_file = tempfile.NamedTemporaryFile(delete=False, suffix=".png")
|
| 102 |
-
temp_file.write(buf.read())
|
| 103 |
-
temp_file.flush()
|
| 104 |
-
temp_file.close()
|
| 105 |
-
|
| 106 |
-
buf.seek(0)
|
| 107 |
-
# Upload to Backblaze B2 in background, don't show result to user
|
| 108 |
-
save_to_b2(buf.getvalue(), key)
|
| 109 |
-
|
| 110 |
-
return temp_file.name, gr.update(visible=True, value="Success! Download your image below.")
|
| 111 |
-
except Exception as e:
|
| 112 |
-
logger.error(f"Encoding failed: {e}")
|
| 113 |
-
return None, gr.update(visible=True, value=f"Error: {str(e)}")
|
| 114 |
|
| 115 |
-
def
|
| 116 |
-
if img is None or not key:
|
| 117 |
-
return "", gr.update(visible=True, value="Please provide image and key.")
|
| 118 |
try:
|
| 119 |
-
|
| 120 |
-
|
|
|
|
|
|
|
|
|
|
| 121 |
if not encrypted_b64:
|
| 122 |
-
return
|
| 123 |
encrypted = base64.b64decode(encrypted_b64).decode()
|
| 124 |
-
|
| 125 |
-
return
|
| 126 |
except Exception as e:
|
| 127 |
-
|
| 128 |
-
return "", gr.update(visible=True, value=f"Error: {str(e)}")
|
| 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 |
if __name__ == "__main__":
|
| 176 |
demo.launch()
|
|
|
|
|
|
|
| 1 |
import gradio as gr
|
| 2 |
+
import os
|
| 3 |
+
import time
|
| 4 |
+
import threading
|
|
|
|
|
|
|
|
|
|
| 5 |
import boto3
|
|
|
|
|
|
|
|
|
|
| 6 |
from botocore.exceptions import ClientError
|
| 7 |
+
from PIL import Image
|
| 8 |
+
import base64
|
| 9 |
+
import smtplib
|
| 10 |
+
from email.message import EmailMessage
|
| 11 |
+
from io import BytesIO
|
| 12 |
|
| 13 |
+
# ==== CONFIGURATION ====
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
B2_KEY_ID = os.environ.get("B2_KEY_ID")
|
| 15 |
B2_APPLICATION_KEY = os.environ.get("B2_APPLICATION_KEY")
|
| 16 |
B2_BUCKET = os.environ.get("B2_BUCKET")
|
| 17 |
+
B2_ENDPOINT = os.environ.get("B2_ENDPOINT") # e.g. https://s3.us-west-002.backblazeb2.com
|
| 18 |
+
|
| 19 |
+
EMAIL_ID = os.environ.get("EMAIL_ID")
|
| 20 |
+
EMAIL_PASSWORD = os.environ.get("EMAIL_PASSWORD") # App password or SMTP password
|
| 21 |
+
EMAIL_SMTP_SERVER = os.environ.get("EMAIL_SMTP_SERVER", "smtp.gmail.com")
|
| 22 |
+
EMAIL_SMTP_PORT = int(os.environ.get("EMAIL_SMTP_PORT") or 587)
|
| 23 |
+
EMAIL_TO = os.environ.get("EMAIL_TO", EMAIL_ID)
|
| 24 |
|
| 25 |
+
PROCESSED_FILES_LOG = "processed_files.txt"
|
| 26 |
+
POLL_INTERVAL = 30 # seconds
|
| 27 |
+
|
| 28 |
+
# ==== GLOBALS ====
|
| 29 |
+
monitor_thread = None
|
| 30 |
+
stop_event = threading.Event()
|
| 31 |
+
log_lines = []
|
| 32 |
+
|
| 33 |
+
# ==== HELPERS ====
|
| 34 |
|
| 35 |
def xor_encrypt_decrypt(text, key):
|
| 36 |
key_repeated = (key * (len(text) // len(key) + 1))[:len(text)]
|
| 37 |
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, key_repeated))
|
| 38 |
|
| 39 |
+
def log(message):
|
| 40 |
+
global log_lines
|
| 41 |
+
ts = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
| 42 |
+
line = f"[{ts}] {message}"
|
| 43 |
+
log_lines.append(line)
|
| 44 |
+
# Keep log window reasonable in size
|
| 45 |
+
if len(log_lines) > 200:
|
| 46 |
+
log_lines = log_lines[-200:]
|
| 47 |
+
|
| 48 |
def get_b2_client():
|
| 49 |
session = boto3.session.Session()
|
| 50 |
s3 = session.client(
|
|
|
|
| 55 |
)
|
| 56 |
return s3
|
| 57 |
|
| 58 |
+
def load_processed_files():
|
| 59 |
+
if not os.path.exists(PROCESSED_FILES_LOG):
|
| 60 |
+
return set()
|
| 61 |
+
with open(PROCESSED_FILES_LOG, "r") as f:
|
| 62 |
+
return set(line.strip() for line in f if line.strip())
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 63 |
|
| 64 |
+
def save_processed_file(filename):
|
| 65 |
+
with open(PROCESSED_FILES_LOG, "a") as f:
|
| 66 |
+
f.write(filename + "\n")
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 67 |
|
| 68 |
+
def extract_key_from_filename(filename):
|
| 69 |
+
return filename.split("_")[0]
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
def decrypt_message_from_fileobj(fileobj, key):
|
|
|
|
|
|
|
| 72 |
try:
|
| 73 |
+
# Read all data into a seekable buffer
|
| 74 |
+
data = fileobj.read()
|
| 75 |
+
buffer = BytesIO(data)
|
| 76 |
+
img = Image.open(buffer)
|
| 77 |
+
encrypted_b64 = img.info.get("encrypted_message")
|
| 78 |
if not encrypted_b64:
|
| 79 |
+
return None, "No encrypted message in image"
|
| 80 |
encrypted = base64.b64decode(encrypted_b64).decode()
|
| 81 |
+
message = xor_encrypt_decrypt(encrypted, key)
|
| 82 |
+
return message, None
|
| 83 |
except Exception as e:
|
| 84 |
+
return None, f"Failed to decrypt: {e}"
|
|
|
|
| 85 |
|
| 86 |
+
def send_email(subject, body):
|
| 87 |
+
try:
|
| 88 |
+
msg = EmailMessage()
|
| 89 |
+
msg["Subject"] = subject
|
| 90 |
+
msg["From"] = EMAIL_ID
|
| 91 |
+
msg["To"] = EMAIL_TO
|
| 92 |
+
msg.set_content(body)
|
| 93 |
+
with smtplib.SMTP(EMAIL_SMTP_SERVER, EMAIL_SMTP_PORT) as smtp:
|
| 94 |
+
smtp.starttls()
|
| 95 |
+
smtp.login(EMAIL_ID, EMAIL_PASSWORD)
|
| 96 |
+
smtp.send_message(msg)
|
| 97 |
+
return True, None
|
| 98 |
+
except Exception as e:
|
| 99 |
+
return False, str(e)
|
| 100 |
+
|
| 101 |
+
def poll_bucket():
|
| 102 |
+
processed = load_processed_files()
|
| 103 |
+
log("Monitoring started.")
|
| 104 |
+
while not stop_event.is_set():
|
| 105 |
+
try:
|
| 106 |
+
s3 = get_b2_client()
|
| 107 |
+
response = s3.list_objects_v2(Bucket=B2_BUCKET)
|
| 108 |
+
files = response.get("Contents", [])
|
| 109 |
+
new_files = [f["Key"] for f in files if f["Key"].endswith(".png") and f["Key"] not in processed]
|
| 110 |
+
if new_files:
|
| 111 |
+
log(f"Found {len(new_files)} new file(s): {', '.join(new_files)}")
|
| 112 |
+
for fname in new_files:
|
| 113 |
+
key = extract_key_from_filename(os.path.basename(fname))
|
| 114 |
+
try:
|
| 115 |
+
fileobj = s3.get_object(Bucket=B2_BUCKET, Key=fname)['Body']
|
| 116 |
+
message, err = decrypt_message_from_fileobj(fileobj, key)
|
| 117 |
+
if err:
|
| 118 |
+
log(f"{fname}: {err}")
|
| 119 |
+
else:
|
| 120 |
+
log(f"{fname}: Decrypted message: {message}")
|
| 121 |
+
subj = f"Decrypted message from {fname}"
|
| 122 |
+
ok, email_err = send_email(subj, message)
|
| 123 |
+
if ok:
|
| 124 |
+
log(f"{fname}: Emailed message to {EMAIL_TO}")
|
| 125 |
+
else:
|
| 126 |
+
log(f"{fname}: Email failed: {email_err}")
|
| 127 |
+
save_processed_file(fname)
|
| 128 |
+
processed.add(fname)
|
| 129 |
+
except ClientError as ce:
|
| 130 |
+
log(f"{fname}: Failed to download/process: {ce}")
|
| 131 |
+
except Exception as e:
|
| 132 |
+
log(f"{fname}: Unexpected error: {e}")
|
| 133 |
+
except Exception as e:
|
| 134 |
+
log(f"Polling error: {e}")
|
| 135 |
+
# Wait before next poll
|
| 136 |
+
for _ in range(POLL_INTERVAL):
|
| 137 |
+
if stop_event.is_set():
|
| 138 |
+
break
|
| 139 |
+
time.sleep(1)
|
| 140 |
+
log("Monitoring stopped.")
|
| 141 |
+
|
| 142 |
+
def start_monitoring():
|
| 143 |
+
global monitor_thread, stop_event
|
| 144 |
+
if monitor_thread and monitor_thread.is_alive():
|
| 145 |
+
log("Already monitoring.")
|
| 146 |
+
return
|
| 147 |
+
stop_event.clear()
|
| 148 |
+
monitor_thread = threading.Thread(target=poll_bucket, daemon=True)
|
| 149 |
+
monitor_thread.start()
|
| 150 |
+
log("Started background polling thread.")
|
| 151 |
|
| 152 |
+
def stop_monitoring():
|
| 153 |
+
global stop_event
|
| 154 |
+
stop_event.set()
|
| 155 |
+
log("Stop signal sent.")
|
| 156 |
|
| 157 |
+
def refresh_log():
|
| 158 |
+
return "\n".join(log_lines[-100:])
|
| 159 |
+
|
| 160 |
+
# ==== GRADIO UI ====
|
| 161 |
+
|
| 162 |
+
with gr.Blocks() as demo:
|
| 163 |
+
gr.Markdown("# 📡 B2 Monitor & Relay Service")
|
| 164 |
+
gr.Markdown("Monitors your Backblaze B2 bucket for new images, decrypts messages using filename key, and relays via email.")
|
| 165 |
+
with gr.Row():
|
| 166 |
+
start_btn = gr.Button("Start Monitoring")
|
| 167 |
+
stop_btn = gr.Button("Stop Monitoring")
|
| 168 |
+
refresh_btn = gr.Button("Refresh Log")
|
| 169 |
+
log_display = gr.Textbox(label="Log", lines=20, interactive=False, value="", show_copy_button=True)
|
| 170 |
+
|
| 171 |
+
def ui_start():
|
| 172 |
+
start_monitoring()
|
| 173 |
+
return refresh_log()
|
| 174 |
+
def ui_stop():
|
| 175 |
+
stop_monitoring()
|
| 176 |
+
return refresh_log()
|
| 177 |
+
def ui_refresh():
|
| 178 |
+
return refresh_log()
|
| 179 |
+
|
| 180 |
+
start_btn.click(ui_start, outputs=log_display)
|
| 181 |
+
stop_btn.click(ui_stop, outputs=log_display)
|
| 182 |
+
refresh_btn.click(ui_refresh, outputs=log_display)
|
| 183 |
+
|
| 184 |
+
# Remove every=10 for Gradio v4+ compatibility
|
| 185 |
+
demo.load(ui_refresh, outputs=log_display)
|
| 186 |
|
| 187 |
if __name__ == "__main__":
|
| 188 |
demo.launch()
|