Create app.py
Browse files123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224import osimport ioimport timeimport requestsfrom flask import Flask, request, jsonify, render_template_stringfrom PIL import Image, ImageOpsfrom huggingface_hub import HfApi
app = 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 do if level == "none": print("π Mode: None (Uploading Original Raw Image)") return image_content
try: img = Image.open(io.BytesIO(image_content)) img = ImageOps.exif_transpose(img) # EXIF data hatao aur sidha karo if img.mode in ("RGBA", "P"): img = img.convert("RGB") # ποΈ Settings Dictionary 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} } # Default fallback 'extreme' par rahega conf = 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 Loop 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"], # β’οΈ BEAST MODE COMPRESSION optimize=True ) size_kb = output.tell() / 1024 if size_kb <= conf["target_kb"]: break curr_q -= 5 # Dheere-dheere quality girao
output.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"}), 400 if not HF_TOKEN or not HF_REPO: return jsonify({"success": False, "error": "HF Secrets missing in Space Settings"}), 500
try: # 1. Image Download resp = 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 Image optimized_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.webp filename = f"img_{int(time.time())}_{os.urandom(3).hex()}.{ext}" path_in_repo = f"posters/{filename}" # 4. Upload to Hugging Face api = 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 Link final_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: return jsonify({"success": False, "error": str(e)}), 500
# --- π₯οΈ UI ROUTE (TESTING DASHBOARD) ---HTML_UI = """<!DOCTYPE html><html lang="en"><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></body></html>"""
@app.route('/')def index(): return render_template_string(HTML_UI)
if __name__ == '__main__': # Docker/HF Spaces uses port 7860 app.run(host='0.0.0.0', port=7860)app.pyAdded+224