bk939448 commited on
Commit
2c5b1a4
Β·
verified Β·
1 Parent(s): 7e550de

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +34 -18
app.py CHANGED
@@ -22,11 +22,11 @@ Image.MAX_IMAGE_PIXELS = None
22
  PENDING_DIR = "pending_uploads"
23
  os.makedirs(PENDING_DIR, exist_ok=True)
24
 
25
- # --- πŸ”„ BACKGROUND BATCH UPLOADER (Har 45 seconds) ---
26
  def background_uploader():
27
  api = HfApi()
28
  while True:
29
- time.sleep(30) # ⏱️ 30 Second Timer
30
  try:
31
  files_to_upload = os.listdir(PENDING_DIR)
32
  if not files_to_upload:
@@ -39,9 +39,18 @@ def background_uploader():
39
 
40
  for filename in files_to_upload:
41
  file_path = os.path.join(PENDING_DIR, filename)
 
 
 
 
 
 
 
 
42
  operations.append(
43
  CommitOperationAdd(
44
- path_in_repo=f"posters/{filename}",
 
45
  path_or_fileobj=file_path
46
  )
47
  )
@@ -53,7 +62,7 @@ def background_uploader():
53
  repo_type="dataset",
54
  token=HF_TOKEN,
55
  operations=operations,
56
- commit_message=f"Batch upload of {len(operations)} images by OptiPix"
57
  )
58
  print("βœ… [BATCH UPLOAD] Success! Local files delete kar rahe hain...")
59
 
@@ -75,9 +84,9 @@ def xor_encrypt_decrypt_bytes(data: bytes, key: str) -> bytes:
75
  key_len = len(key_bytes)
76
  return bytes([b ^ key_bytes[i % key_len] for i, b in enumerate(data)])
77
 
78
- def encrypt_filename(filename: str, key: str) -> str:
79
- """Filename ko encrypt karke base64 URL-safe banata hai"""
80
- xored = "".join(chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(filename))
81
  return base64.urlsafe_b64encode(xored.encode()).decode().rstrip("=")
82
 
83
  # --- 🧠 SUPER-OPTIMIZER LOGIC ---
@@ -142,24 +151,32 @@ def handle_upload():
142
  if not image_content:
143
  return jsonify({"success": False, "error": "No file or URL provided"}), 400
144
 
145
- # Optimize & Encrypt
146
  optimized_data = dynamic_optimize(image_content, comp_level)
147
  encrypted_image_data = xor_encrypt_decrypt_bytes(optimized_data, XOR_KEY)
148
 
149
- # Generate Filenames
150
- real_filename = f"img_{int(time.time())}_{os.urandom(3).hex()}.webp"
151
- encrypted_filename = encrypt_filename(real_filename, XOR_KEY)
 
 
 
 
 
 
 
 
 
152
 
153
- # Save to Local Queue instead of Direct Upload
154
  local_filepath = os.path.join(PENDING_DIR, real_filename)
155
  with open(local_filepath, "wb") as f:
156
  f.write(encrypted_image_data)
157
 
158
  # Create Final Worker URL
159
  worker_base = WORKER_URL if WORKER_URL.endswith('/') else WORKER_URL + '/'
160
- final_cf_url = f"{worker_base}{encrypted_filename}"
161
 
162
- # Exact Same JSON Response!
163
  return jsonify({
164
  "success": True,
165
  "url": final_cf_url,
@@ -240,7 +257,7 @@ HTML_UI = """
240
  </div>
241
 
242
  <div class="notice-text">
243
- ⏳ Note: The image URL will be live in max 45 seconds.
244
  </div>
245
 
246
  <img id="resImg" class="preview-img" src="" alt="Preview will load soon...">
@@ -275,13 +292,12 @@ HTML_UI = """
275
  document.getElementById('oldSize').innerText = data.original_size_kb;
276
  document.getElementById('newSize').innerText = data.encrypted_size_kb;
277
 
278
- // Pehle image src hatayenge taaki broken image na dikhe timer ke dauran
279
  document.getElementById('resImg').src = "";
280
 
281
- // 45 seconds baad automatically image reload karwane ka try karenge preview ke liye
282
  setTimeout(() => {
283
  document.getElementById('resImg').src = data.url;
284
- }, 46000);
285
 
286
  resDiv.style.display = "block";
287
  } else {
 
22
  PENDING_DIR = "pending_uploads"
23
  os.makedirs(PENDING_DIR, exist_ok=True)
24
 
25
+ # --- πŸ”„ BACKGROUND BATCH UPLOADER (Har 30 seconds) ---
26
  def background_uploader():
27
  api = HfApi()
28
  while True:
29
+ time.sleep(30) # ⏱️ 30 Second Timer (Tune bola tha)
30
  try:
31
  files_to_upload = os.listdir(PENDING_DIR)
32
  if not files_to_upload:
 
39
 
40
  for filename in files_to_upload:
41
  file_path = os.path.join(PENDING_DIR, filename)
42
+
43
+ # πŸ—‚οΈ 10k LIMIT BYPASS: Smart Folder System (Max ~9000 safe capacity)
44
+ # Naam (img_177237_3a7b9c.webp) me se '3a7' nikalega. Isse 4096 alag folders banenge!
45
+ try:
46
+ sub_folder = filename.split('_')[2][:3]
47
+ except:
48
+ sub_folder = "misc"
49
+
50
  operations.append(
51
  CommitOperationAdd(
52
+ # Ab file 'posters/3a7/img_xxx.webp' me jayegi
53
+ path_in_repo=f"posters/{sub_folder}/{filename}",
54
  path_or_fileobj=file_path
55
  )
56
  )
 
62
  repo_type="dataset",
63
  token=HF_TOKEN,
64
  operations=operations,
65
+ commit_message=f"Batch upload of {len(operations)} images by OptiPix (Sharded)"
66
  )
67
  print("βœ… [BATCH UPLOAD] Success! Local files delete kar rahe hain...")
68
 
 
84
  key_len = len(key_bytes)
85
  return bytes([b ^ key_bytes[i % key_len] for i, b in enumerate(data)])
86
 
87
+ def encrypt_text(text: str, key: str) -> str:
88
+ """Ab ye sidha target URL ko encrypt karega"""
89
+ xored = "".join(chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(text))
90
  return base64.urlsafe_b64encode(xored.encode()).decode().rstrip("=")
91
 
92
  # --- 🧠 SUPER-OPTIMIZER LOGIC ---
 
151
  if not image_content:
152
  return jsonify({"success": False, "error": "No file or URL provided"}), 400
153
 
154
+ # Optimize & Encrypt Data
155
  optimized_data = dynamic_optimize(image_content, comp_level)
156
  encrypted_image_data = xor_encrypt_decrypt_bytes(optimized_data, XOR_KEY)
157
 
158
+ # Generate Unique Filename
159
+ hex_random = os.urandom(3).hex()
160
+ real_filename = f"img_{int(time.time())}_{hex_random}.webp"
161
+
162
+ # πŸ—‚οΈ Calculate Sub-folder based on logic
163
+ sub_folder = hex_random[:3]
164
+
165
+ # 🌐 ASLI JADU: Poora Target URL banao
166
+ full_hf_url = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/posters/{sub_folder}/{real_filename}"
167
+
168
+ # πŸ” URL ko encrypt karo taaki worker ko de sake
169
+ encrypted_url_payload = encrypt_text(full_hf_url, XOR_KEY)
170
 
171
+ # Save to Local Queue
172
  local_filepath = os.path.join(PENDING_DIR, real_filename)
173
  with open(local_filepath, "wb") as f:
174
  f.write(encrypted_image_data)
175
 
176
  # Create Final Worker URL
177
  worker_base = WORKER_URL if WORKER_URL.endswith('/') else WORKER_URL + '/'
178
+ final_cf_url = f"{worker_base}{encrypted_url_payload}"
179
 
 
180
  return jsonify({
181
  "success": True,
182
  "url": final_cf_url,
 
257
  </div>
258
 
259
  <div class="notice-text">
260
+ ⏳ Note: The image URL will be live in max 30 seconds.
261
  </div>
262
 
263
  <img id="resImg" class="preview-img" src="" alt="Preview will load soon...">
 
292
  document.getElementById('oldSize').innerText = data.original_size_kb;
293
  document.getElementById('newSize').innerText = data.encrypted_size_kb;
294
 
 
295
  document.getElementById('resImg').src = "";
296
 
297
+ // 30 seconds wait timeout (plus 1s buffer)
298
  setTimeout(() => {
299
  document.getElementById('resImg').src = data.url;
300
+ }, 31000);
301
 
302
  resDiv.style.display = "block";
303
  } else {