Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -1,50 +1,34 @@
|
|
| 1 |
-
import gradio as gr
|
| 2 |
import os
|
| 3 |
-
import
|
| 4 |
-
import
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 26 |
-
|
| 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,134 +39,138 @@ def get_b2_client():
|
|
| 55 |
)
|
| 56 |
return s3
|
| 57 |
|
| 58 |
-
def
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
return filename.split("_")[0]
|
| 70 |
|
| 71 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
try:
|
| 73 |
-
#
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 83 |
except Exception as e:
|
| 84 |
-
|
| 85 |
|
| 86 |
-
def
|
|
|
|
|
|
|
| 87 |
try:
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
except Exception as e:
|
| 99 |
-
|
| 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
|
| 153 |
-
|
| 154 |
-
|
| 155 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 156 |
|
| 157 |
-
|
| 158 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 159 |
|
| 160 |
-
|
|
|
|
|
|
|
| 161 |
|
| 162 |
-
|
| 163 |
-
|
| 164 |
-
|
| 165 |
-
|
| 166 |
-
|
| 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()
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
+
import gradio as gr
|
| 3 |
+
from PIL import Image, PngImagePlugin
|
| 4 |
+
import io
|
| 5 |
+
import random
|
| 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 |
+
# Configure logging
|
| 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., https://s3.us-west-002.backblazeb2.com
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 24 |
|
| 25 |
+
def random_key(length=16):
|
| 26 |
+
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
)
|
| 40 |
return s3
|
| 41 |
|
| 42 |
+
def get_oldest_b2_file(s3, bucket):
|
| 43 |
+
try:
|
| 44 |
+
response = s3.list_objects_v2(Bucket=bucket)
|
| 45 |
+
if 'Contents' not in response or not response['Contents']:
|
| 46 |
+
return None
|
| 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 save_to_b2(image_bytes, key):
|
| 55 |
+
if not (B2_KEY_ID and B2_APPLICATION_KEY and B2_BUCKET and B2_ENDPOINT):
|
| 56 |
+
logger.error("Backblaze B2 credentials not configured.")
|
| 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 encode_image(image, input_text, key):
|
| 90 |
+
if image is None or not input_text or not key:
|
| 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 decode_image(img, key):
|
| 116 |
+
if img is None or not key:
|
| 117 |
+
return "", gr.update(visible=True, value="Please provide image and key.")
|
| 118 |
+
try:
|
| 119 |
+
pil_img = Image.open(img)
|
| 120 |
+
encrypted_b64 = pil_img.info.get("encrypted_message")
|
| 121 |
+
if not encrypted_b64:
|
| 122 |
+
return "", gr.update(visible=True, value="No encrypted text found in this image.")
|
| 123 |
+
encrypted = base64.b64decode(encrypted_b64).decode()
|
| 124 |
+
decrypted = xor_encrypt_decrypt(encrypted, key)
|
| 125 |
+
return decrypted, gr.update(visible=False)
|
| 126 |
+
except Exception as e:
|
| 127 |
+
logger.error(f"Decoding failed: {e}")
|
| 128 |
+
return "", gr.update(visible=True, value=f"Error: {str(e)}")
|
| 129 |
|
| 130 |
+
with gr.Blocks() as demo:
|
| 131 |
+
gr.Markdown("Image Tools v3")
|
| 132 |
+
with gr.Tab("ENC (Encode)"):
|
| 133 |
+
with gr.Row():
|
| 134 |
+
with gr.Column():
|
| 135 |
+
image_enc = gr.Image(label="Upload Image", type="pil")
|
| 136 |
+
input_text = gr.Textbox(label="Input text", lines=5, placeholder="Enter your text here...")
|
| 137 |
+
with gr.Row():
|
| 138 |
+
key_enc = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key or generate one")
|
| 139 |
+
gen_key_btn = gr.Button("🔑 Generate random key")
|
| 140 |
+
start_btn = gr.Button("Start")
|
| 141 |
+
download_link = gr.File(label="Download image with encrypted message", visible=False)
|
| 142 |
+
enc_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
| 143 |
+
|
| 144 |
+
with gr.Tab("DEC (Decode)"):
|
| 145 |
+
with gr.Row():
|
| 146 |
+
with gr.Column():
|
| 147 |
+
image_dec = gr.Image(label="Upload Image With Encrypted Text", type="filepath")
|
| 148 |
+
key_dec = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key used for encryption")
|
| 149 |
+
dec_btn = gr.Button("Decrypt")
|
| 150 |
+
output_text = gr.Textbox(label="Decrypted Message", lines=5, interactive=False)
|
| 151 |
+
dec_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
| 152 |
+
|
| 153 |
+
gen_key_btn.click(lambda: random_key(), [], key_enc)
|
| 154 |
+
|
| 155 |
+
def on_start(image, text, key):
|
| 156 |
+
result, status = encode_image(image, text, key)
|
| 157 |
+
return result, gr.update(visible=bool(result)), status
|
| 158 |
+
|
| 159 |
+
start_btn.click(
|
| 160 |
+
on_start,
|
| 161 |
+
inputs=[image_enc, input_text, key_enc],
|
| 162 |
+
outputs=[download_link, download_link, enc_status]
|
| 163 |
+
)
|
| 164 |
|
| 165 |
+
def on_decrypt(image_path, key):
|
| 166 |
+
result, status = decode_image(image_path, key)
|
| 167 |
+
return result, status
|
| 168 |
|
| 169 |
+
dec_btn.click(
|
| 170 |
+
on_decrypt,
|
| 171 |
+
inputs=[image_dec, key_dec],
|
| 172 |
+
outputs=[output_text, dec_status]
|
| 173 |
+
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 174 |
|
| 175 |
if __name__ == "__main__":
|
| 176 |
demo.launch()
|