Update app.py
Browse files1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281296 unmodified lines1361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122136 unmodified lines2202212222232241 unmodified lineimport ioimport timeimport requestsfrom flask import Flask, request, jsonify, render_template_stringfrom PIL import Image, ImageOpsfrom huggingface_hub import HfApiapp = Flask(__name__)# --- βοΈ SECRETS (Environment Variables se aayenge) ---HF_TOKEN = os.environ.get("HF_TOKEN")HF_REPO = os.environ.get("HF_REPO")Image.MAX_IMAGE_PIXELS = None# --- π§ SUPER-OPTIMIZER LOGIC ---def dynamic_optimize(image_content, level="extreme"):"""Image ko user ke level ke hisab se optimize karta hai.Levels: none, extreme, high, medium, low"""# π NONE MODE: Bina chhue original image wapas kar doif level == "none":print("π Mode: None (Uploading Original Raw Image)")return image_contenttry:img = Image.open(io.BytesIO(image_content))img = ImageOps.exif_transpose(img) # EXIF data hatao aur sidha karoif img.mode in ("RGBA", "P"):img = img.convert("RGB")# ποΈ Settings Dictionarysettings = {"extreme": {"width": 550, "quality": 70, "method": 6, "target_kb": 60},"high": {"width": 650, "quality": 80, "method": 5, "target_kb": 90},"medium": {"width": 800, "quality": 85, "method": 4, "target_kb": 150},"low": {"width": 1000, "quality": 95, "method": 3, "target_kb": 300}}# Default fallback 'extreme' par rahegaconf = settings.get(level, settings["extreme"])# π Resize Logic (Lanczos algorithm for best quality)if img.width > conf["width"]:ratio = conf["width"] / float(img.width)new_height = int((float(img.height) * float(ratio)))img = img.resize((conf["width"], new_height), Image.Resampling.LANCZOS)# π§ͺ Advanced Compression Loopoutput = io.BytesIO()curr_q = conf["quality"]while curr_q > 10:output.seek(0)output.truncate(0)img.save(output,format='WEBP',quality=curr_q,method=conf["method"], # β’οΈ BEAST MODE COMPRESSIONoptimize=True)size_kb = output.tell() / 1024if size_kb <= conf["target_kb"]:breakcurr_q -= 5 # Dheere-dheere quality giraooutput.seek(0)return output.getvalue()except Exception as e:print(f"β Optimization Error: {e}")return image_content # Agar error aaye to original bhej do# --- π API ROUTE ---@app.route('/upload-poster', methods=['GET'])def handle_upload():img_url = request.args.get('url')comp_level = request.args.get('level', 'extreme').lower()if not img_url:return jsonify({"success": False, "error": "No URL provided"}), 400if not HF_TOKEN or not HF_REPO:return jsonify({"success": False, "error": "HF Secrets missing in Space Settings"}), 500try:# 1. Image Downloadresp = requests.get(img_url, timeout=20)if resp.status_code != 200:return jsonify({"success": False, "error": f"Download failed (Status: {resp.status_code})"}), 400# 2. Process Imageoptimized_data = dynamic_optimize(resp.content, comp_level)# 3. Extension and Stealth Filename Logic# Agar mode 'none' hai to original extension rakho, warna 'webp'ext = img_url.split('.')[-1].split('?')[0].lower()if comp_level != "none" or ext not in ['jpg', 'jpeg', 'png', 'webp', 'gif']:ext = "webp"# Random name generation: img_1712345_abc123.webpfilename = f"img_{int(time.time())}_{os.urandom(3).hex()}.{ext}"path_in_repo = f"posters/{filename}"# 4. Upload to Hugging Faceapi = HfApi()api.upload_file(path_or_fileobj=optimized_data,path_in_repo=path_in_repo,repo_id=HF_REPO,repo_type="dataset",token=HF_TOKEN)# 5. Generate Direct Linkfinal_url = f"https://huggingface.co/datasets/{HF_REPO}/resolve/main/{path_in_repo}"return jsonify({"success": True,"url": final_url,"level_used": comp_level,"original_size_kb": round(len(resp.content)/1024, 2),"new_size_kb": round(len(optimized_data)/1024, 2)})except Exception as e:6 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>HF Poster API | Stealth Mode</title><style>body { font-family: 'Courier New', Courier, monospace; background: #0b0f19; color: #00ffcc; padding: 20px; max-width: 800px; margin: auto; }.card { background: #111827; padding: 25px; border-radius: 12px; box-shadow: 0 0 20px rgba(0, 255, 204, 0.2); border: 1px solid #1f2937; }h2 { color: #fff; border-bottom: 2px solid #00ffcc; padding-bottom: 10px; }input, select, button { width: 100%; padding: 14px; margin: 12px 0; border-radius: 8px; border: 1px solid #374151; box-sizing: border-box; font-size: 16px; font-family: 'Courier New', Courier, monospace;}input, select { background: #1f2937; color: #fff; outline: none; transition: 0.3s;}input:focus, select:focus { border-color: #00ffcc; box-shadow: 0 0 8px rgba(0, 255, 204, 0.5);}button { background: #00ffcc; color: #000; font-weight: bold; cursor: pointer; transition: 0.3s; text-transform: uppercase; letter-spacing: 1px;}button:hover { background: #00ccaa; box-shadow: 0 0 15px rgba(0, 255, 204, 0.6); }button:disabled { background: #374151; color: #9ca3af; cursor: not-allowed; box-shadow: none; }#result { margin-top: 25px; padding: 20px; background: rgba(0, 255, 204, 0.1); border-left: 4px solid #00ffcc; border-radius: 5px; display: none; word-wrap: break-word;}img { max-width: 100%; border-radius: 8px; margin-top: 15px; border: 1px solid #374151;}.stats { display: flex; justify-content: space-between; font-weight: bold; font-size: 15px; margin-top: 15px; color: #fff; background: #1f2937; padding: 10px; border-radius: 5px;}.tag { background: #00ffcc; color: #000; padding: 2px 8px; border-radius: 12px; font-size: 12px; font-weight: bold; margin-left: 10px; vertical-align: middle;}</style></head><body><div class="card"><h2>π Skynet Poster API <span class="tag">v3.0</span></h2><input type="text" id="imgUrl" placeholder="π Paste Raw Image URL here..." required><select id="level"><option value="none">π None (Original Quality, Bypass Compression)</option><option value="extreme" selected>π Extreme (Max Compression, ~60KB, Method 6)</option><option value="high">π High (~90KB, Method 5)</option><option value="medium">π Medium (~150KB, Method 4)</option><option value="low">π Low (Max Quality, ~300KB, Method 3)</option></select><button onclick="uploadImage()" id="btn">β‘ Execute API Call</button><div id="result"><h3 style="margin:0 0 10px 0; color:#00ffcc;">β Upload Successful!</h3><a id="resLink" href="#" target="_blank" style="color:#60a5fa; text-decoration: none; font-weight: bold;">[View Direct Image]</a><div class="stats"><span id="oldSize">Original: -- KB</span><span id="newSize" style="color:#00ffcc;">Compressed: -- KB</span></div><img id="resImg" src="" alt="Compressed Output"></div></div><script>async function uploadImage() {const btn = document.getElementById('btn');const url = document.getElementById('imgUrl').value;const level = document.getElementById('level').value;const resDiv = document.getElementById('result');if(!url) { alert("Bhai, URL to daal! π"); return; }btn.innerText = "β³ Processing (HF CPUs are crushing pixels...)";btn.disabled = true;resDiv.style.display = "none";try {const response = await fetch(`/upload-poster?url=${encodeURIComponent(url)}&level=${level}`);const data = await response.json();if(data.success) {document.getElementById('resLink').href = data.url;document.getElementById('resLink').innerText = data.url;document.getElementById('resImg').src = data.url;document.getElementById('oldSize').innerText = `Original: ${data.original_size_kb} KB`;document.getElementById('newSize').innerText = `New: ${data.new_size_kb} KB`;resDiv.style.display = "block";} else {alert("β Error: " + data.error);}} catch (err) {alert("β Network Error! Is the Space awake?");}btn.innerText = "β‘ Execute API Call";btn.disabled = false;}</script>6 unmodified linesreturn render_template_string(HTML_UI)if __name__ == '__main__':# Docker/HF Spaces uses port 7860app.run(host='0.0.0.0', port=7860)1 unmodified line234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321336 unmodified lines1401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282296 unmodified lines2362372382391 unmodified lineimport ioimport timeimport requestsimport base64from flask import Flask, request, jsonify, render_template_stringfrom PIL import Image, ImageOpsfrom huggingface_hub import HfApiapp = Flask(__name__)# --- βοΈ SECRETS (Environment Variables) ---HF_TOKEN = os.environ.get("HF_TOKEN")HF_REPO = os.environ.get("HF_REPO")WORKER_URL = os.environ.get("WORKER_URL", "https://your-worker.subdomain.workers.dev/") # CF Worker URLXOR_KEY = os.environ.get("XOR_KEY", "badal_master_key") # Tumhari Secret Chabi πImage.MAX_IMAGE_PIXELS = None# --- π XOR ENCRYPTION ENGINE ---def xor_encrypt_decrypt_bytes(data: bytes, key: str) -> bytes:"""Image ke binary data ko corrupt/decrypt karta hai"""key_bytes = key.encode()key_len = len(key_bytes)# Python me bytes ko XOR karnareturn bytes([b ^ key_bytes[i % key_len] for i, b in enumerate(data)])def encrypt_filename(filename: str, key: str) -> str:"""Filename ko encrypt karke base64 URL-safe banata hai"""xored = "".join(chr(ord(c) ^ ord(key[i % len(key)])) for i, c in enumerate(filename))# Padding hata dete hain taaki URL clean dikhereturn base64.urlsafe_b64encode(xored.encode()).decode().rstrip("=")# --- π§ SUPER-OPTIMIZER LOGIC ---def dynamic_optimize(image_content, level="extreme"):"""Image ko optimize karta hai"""if level == "none":return image_contenttry:img = Image.open(io.BytesIO(image_content))img = ImageOps.exif_transpose(img)if img.mode in ("RGBA", "P"): img = img.convert("RGB")settings = {"extreme": {"width": 550, "quality": 70, "method": 6, "target_kb": 60},"high": {"width": 650, "quality": 80, "method": 5, "target_kb": 90},"medium": {"width": 800, "quality": 85, "method": 4, "target_kb": 150},"low": {"width": 1000, "quality": 95, "method": 3, "target_kb": 300}}conf = settings.get(level, settings["extreme"])if img.width > conf["width"]:ratio = conf["width"] / float(img.width)img = img.resize((conf["width"], int(float(img.height) * ratio)), Image.Resampling.LANCZOS)output = io.BytesIO()curr_q = conf["quality"]while curr_q > 10:output.seek(0)output.truncate(0)img.save(output, format='WEBP', quality=curr_q, method=conf["method"], optimize=True)if (output.tell() / 1024) <= conf["target_kb"]: breakcurr_q -= 5return output.getvalue()except Exception as e:print(f"β Optimization Error: {e}")return image_content# --- π API ROUTE (Handles BOTH URL and DIRECT FILE) ---@app.route('/upload-poster', methods=['GET', 'POST'])def handle_upload():comp_level = request.args.get('level', request.form.get('level', 'extreme')).lower()image_content = Noneif not HF_TOKEN or not HF_REPO:return jsonify({"success": False, "error": "HF Secrets missing!"}), 500try:# 1. Check if Direct File Uploadif 'file' in request.files and request.files['file'].filename != '':file = request.files['file']image_content = file.read()# 2. Check if URL Uploadelif request.args.get('url') or request.form.get('url'):img_url = request.args.get('url') or request.form.get('url')resp = requests.get(img_url, timeout=20)if resp.status_code != 200:return jsonify({"success": False, "error": "URL Download failed"}), 400image_content = resp.contentif not image_content:return jsonify({"success": False, "error": "No file or URL provided"}), 400# 3. Optimize Imageoptimized_data = dynamic_optimize(image_content, comp_level)# 4. π ENCRYPT THE IMAGE DATA (Magic Happens Here!)encrypted_image_data = xor_encrypt_decrypt_bytes(optimized_data, XOR_KEY)# 5. Generate Real Filename & Encrypt itreal_filename = f"img_{int(time.time())}_{os.urandom(3).hex()}.webp"encrypted_filename = encrypt_filename(real_filename, XOR_KEY)path_in_repo = f"posters/{real_filename}"# 6. Upload ENCRYPTED GARBAGE to Hugging Faceapi = HfApi()api.upload_file(path_or_fileobj=encrypted_image_data, # Uploading corrupted bytespath_in_repo=path_in_repo,repo_id=HF_REPO,repo_type="dataset",token=HF_TOKEN)# 7. Create Final Worker URL for Userworker_base = WORKER_URL if WORKER_URL.endswith('/') else WORKER_URL + '/'final_cf_url = f"{worker_base}{encrypted_filename}"return jsonify({"success": True,"url": final_cf_url, # Cloudflare Worker URL with Encrypted Name"real_hf_filename": real_filename, # (Just for debugging, DB me mat dalna)"level_used": comp_level,"original_size_kb": round(len(image_content)/1024, 2),"encrypted_size_kb": round(len(encrypted_image_data)/1024, 2)})except Exception as e:6 unmodified lines<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>Skynet DMCA Killer</title><style>body { font-family: 'Courier New', Courier, monospace; background: #050505; color: #0f0; padding: 20px; max-width: 800px; margin: auto; }.card { background: #111; padding: 25px; border-radius: 8px; border: 1px solid #0f0; box-shadow: 0 0 15px rgba(0, 255, 0, 0.2); }h2 { color: #0f0; border-bottom: 1px dashed #0f0; padding-bottom: 10px; text-transform: uppercase; }.input-group { background: #1a1a1a; padding: 15px; border-radius: 5px; margin-bottom: 15px; border: 1px solid #333; }input[type="text"], input[type="file"], select { width: 100%; padding: 12px; margin: 8px 0; background: #000; color: #0f0; border: 1px solid #0f0; outline: none; box-sizing: border-box; }button { width: 100%; padding: 15px; background: #0f0; color: #000; font-weight: bold; border: none; cursor: pointer; text-transform: uppercase; margin-top: 10px; font-size: 16px; }button:hover { background: #fff; color: #000; }button:disabled { background: #333; color: #666; cursor: not-allowed; }#result { margin-top: 25px; padding: 15px; background: #002200; border-left: 4px solid #0f0; display: none; word-wrap: break-word; }.url-box { background: #000; padding: 10px; border: 1px dashed #0f0; margin: 10px 0; font-size: 14px; }.stats { display: flex; justify-content: space-between; font-weight: bold; font-size: 14px; margin-top: 10px; color: #fff; }</style></head><body><div class="card"><h2>π‘οΈ DMCA Killer v4.0 (XOR Encrypted)</h2><div class="input-group"><label><b>Option 1: Paste Image URL</b></label><input type="text" id="imgUrl" placeholder="π https://example.com/movie.jpg"></div><div class="input-group"><label><b>Option 2: Direct File Upload</b></label><input type="file" id="imgFile" accept="image/*"></div><select id="level"><option value="none">π None (Original Quality, Bypass Compression)</option><option value="extreme" selected>π Extreme (Max Compression, ~60KB)</option><option value="medium">π Medium (~150KB)</option></select><button onclick="uploadImage()" id="btn">β‘ Encrypt & Deploy to HF</button><div id="result"><h3 style="margin:0 0 10px 0;">β DEPLOYMENT SUCCESSFUL</h3><p style="margin: 0; color: #aaa;">Cloudflare Worker URL (Safe for DB):</p><div class="url-box" id="resLink"></div><div class="stats"><span id="oldSize">Original: -- KB</span><span id="newSize" style="color:#0f0;">Encrypted: -- KB</span></div><p style="margin-top: 10px; font-size: 12px; color: yellow;">β οΈ Note: This URL will only work if your Cloudflare Worker is active!</p></div></div><script>async function uploadImage() {const btn = document.getElementById('btn');const urlInput = document.getElementById('imgUrl').value;const fileInput = document.getElementById('imgFile').files[0];const level = document.getElementById('level').value;const resDiv = document.getElementById('result');if(!urlInput && !fileInput) { alert("Please provide a URL or select a File!"); return; }btn.innerText = "β³ Encrypting Data & Uploading...";btn.disabled = true;resDiv.style.display = "none";let formData = new FormData();formData.append('level', level);if(fileInput) formData.append('file', fileInput);else formData.append('url', urlInput);try {const response = await fetch('/upload-poster', { method: 'POST', body: formData });const data = await response.json();if(data.success) {document.getElementById('resLink').innerText = data.url;document.getElementById('oldSize').innerText = `Original: ${data.original_size_kb} KB`;document.getElementById('newSize').innerText = `Encrypted: ${data.encrypted_size_kb} KB`;resDiv.style.display = "block";} else {alert("β Error: " + data.error);}} catch (err) {alert("β Critical Network Error!");}btn.innerText = "β‘ Encrypt & Deploy to HF";btn.disabled = false;}</script>6 unmodified linesreturn render_template_string(HTML_UI)if __name__ == '__main__':app.run(host='0.0.0.0', port=7860)
app.py+113-98