Upload 3 files
Browse filesFiles changed (3)
- DockerfileAdded+20
- index.htmlAdded+340
- web_app.pyAdded+237
1234567891011121314151617181920# Use a lightweight Python imageFROM python:3.9-slim
# Install pngquant, jpegoptim and zipRUN apt-get update && \ apt-get install -y pngquant jpegoptim zip && \ rm -rf /var/lib/apt/lists/*
# Set working directoryWORKDIR /app
# Copy application filesCOPY web_app.py .COPY index.html .
# Expose the port (optional documentation)EXPOSE 8989
# Start the applicationCMD ["python", "web_app.py"]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>TinyPNG Local</title> <style> :root { --primary: #5ec75e; --bg: #f5f7fa; --text: #333; --card-bg: #fff; } body { font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background-color: var(--bg); color: var(--text); margin: 0; padding: 0; display: flex; flex-direction: column; align-items: center; min-height: 100vh; } header { background: #fff; width: 100%; padding: 1rem 0; text-align: center; box-shadow: 0 2px 10px rgba(0,0,0,0.05); margin-bottom: 2rem; } h1 { margin: 0; color: #333; display: flex; align-items: center; justify-content: center; gap: 10px;} .container { width: 90%; max-width: 800px; background: var(--card-bg); border-radius: 12px; padding: 2rem; box-shadow: 0 4px 20px rgba(0,0,0,0.05); margin-bottom: 3rem; }
#drop-zone { border: 3px dashed #d0d7de; border-radius: 12px; padding: 3rem; text-align: center; cursor: pointer; transition: all 0.2s; background: #fafbfc; } #drop-zone:hover, #drop-zone.dragover { border-color: var(--primary); background: #f0fff0; } #drop-zone p { font-size: 1.2rem; color: #666; margin: 10px 0 0; } .icon { font-size: 3rem; }
.toolbar { display: flex; justify-content: space-between; align-items: center; margin-top: 2rem; padding-bottom: 10px; border-bottom: 2px solid #f0f0f0; } .btn-action { background: #333; color: white; border: none; padding: 10px 20px; border-radius: 6px; font-size: 1rem; cursor: pointer; transition: background 0.2s; text-decoration: none; display: inline-flex; align-items: center; gap: 5px; } .btn-action:hover { background: #555; } .btn-action:disabled { background: #ccc; cursor: not-allowed; } .btn-download-all { background: var(--primary); } .btn-download-all:hover { background: #4db04d; }
#file-list { width: 100%; border-collapse: collapse; margin-top: 10px; } #file-list th, #file-list td { text-align: left; padding: 12px; border-bottom: 1px solid #eee; } #file-list th { color: #888; font-weight: 500; font-size: 0.9rem; } .status-pending { color: #888; } .status-processing { color: #e6a23c; } .status-done { color: var(--primary); font-weight: bold; } .status-error { color: #f56c6c; }
.btn-download { background: var(--primary); color: white; text-decoration: none; padding: 6px 12px; border-radius: 4px; font-size: 0.9rem; display: inline-block; transition: opacity 0.2s; } .btn-download:hover { opacity: 0.9; } .progress-bar { height: 4px; background: #eee; border-radius: 2px; overflow: hidden; width: 100px; display: inline-block; vertical-align: middle; margin-right: 10px; } .progress-fill { height: 100%; background: var(--primary); width: 0%; transition: width 0.3s; }
/* Hidden input */ #file-input { display: none; } .hidden { display: none; } </style></head><body>
<header> <h1><span>🐼</span> TinyPNG Local</h1></header>
<div class="container"> <div id="drop-zone"> <div class="icon">📂</div> <p>Drag & drop PNG or JPG images here</p> <div style="font-size: 0.9rem; color: #999; margin-top: 5px;">or click to select files</div> </div> <input type="file" id="file-input" multiple accept="image/png,image/jpeg,image/jpg">
<div id="result-area" class="hidden"> <div class="toolbar"> <div style="font-weight: bold; color: #666;">Processed Files</div> <button id="btn-zip" class="btn-action btn-download-all" disabled> ⬇️ Download All as ZIP </button> </div>
<table id="file-list"> <thead> <tr> <th>File Name</th> <th>Original</th> <th>Compressed</th> <th>Status</th> <th>Action</th> </tr> </thead> <tbody> <!-- Items will be added here --> </tbody> </table> </div></div>
<script> const dropZone = document.getElementById('drop-zone'); const fileInput = document.getElementById('file-input'); const resultArea = document.getElementById('result-area'); const fileListTable = document.getElementById('file-list'); const tbody = fileListTable.querySelector('tbody'); const btnZip = document.getElementById('btn-zip');
let processedFiles = []; // Store paths for zip
// Drag & Drop handlers dropZone.addEventListener('click', () => fileInput.click()); dropZone.addEventListener('dragover', (e) => { e.preventDefault(); dropZone.classList.add('dragover'); }); dropZone.addEventListener('dragleave', () => dropZone.classList.remove('dragover')); dropZone.addEventListener('drop', (e) => { e.preventDefault(); dropZone.classList.remove('dragover'); handleFiles(e.dataTransfer.files); }); fileInput.addEventListener('change', (e) => handleFiles(e.target.files)); btnZip.addEventListener('click', downloadZip);
function formatSize(bytes) { if (bytes === 0) return '0 B'; const k = 1024; const sizes = ['B', 'KB', 'MB', 'GB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]; }
function handleFiles(files) { if (files.length > 0) { resultArea.classList.remove('hidden'); } Array.from(files).forEach(file => { if (!file.type.match('image.*')) return; uploadFile(file); }); }
function uploadFile(file) { const row = document.createElement('tr'); row.innerHTML = ` <td>${file.name}</td> <td>${formatSize(file.size)}</td> <td>...</td> <td> <div class="progress-bar"><div class="progress-fill" style="width: 0%"></div></div> <span class="status-text status-pending">Pending</span> </td> <td>-</td> `; tbody.appendChild(row);
// Upload const xhr = new XMLHttpRequest(); // Encode filename to handle special characters safely in header const encodedName = encodeURIComponent(file.name); xhr.open('POST', `/upload?filename=${encodedName}`, true); // We send raw bytes xhr.setRequestHeader('Content-Type', 'application/octet-stream');
xhr.upload.onprogress = (e) => { if (e.lengthComputable) { const percent = (e.loaded / e.total) * 100; row.querySelector('.progress-fill').style.width = percent + '%'; if (percent === 100) { row.querySelector('.status-text').textContent = 'Compressing...'; row.querySelector('.status-text').className = 'status-text status-processing'; } } };
xhr.onload = () => { if (xhr.status === 200) { const result = JSON.parse(xhr.responseText); if (result.status === 'success' || result.status === 'skipped') { const savedPercent = ((result.original_size - result.new_size) / result.original_size * 100).toFixed(1); row.querySelector('td:nth-child(3)').textContent = formatSize(result.new_size); let statusHtml = ''; if (result.status === 'skipped') { statusHtml = `<span class="status-done" style="color:#e6a23c">Skipped (Larger)</span>`; } else { statusHtml = `<span class="status-done">Done (-${savedPercent}%)</span>`; } row.querySelector('td:nth-child(4)').innerHTML = statusHtml; // Download button const downloadUrl = `/download?path=${encodeURIComponent(result.path)}`; row.querySelector('td:nth-child(5)').innerHTML = `<a href="${downloadUrl}" class="btn-download" download="${file.name}">Download</a>`; // Add to processed list for zip processedFiles.push(result.path); btnZip.disabled = false; } else { row.querySelector('.status-text').textContent = 'Error'; row.querySelector('.status-text').className = 'status-text status-error'; } } else { row.querySelector('.status-text').textContent = 'Error'; row.querySelector('.status-text').className = 'status-text status-error'; } };
xhr.send(file); }
function downloadZip() { if (processedFiles.length === 0) return; btnZip.textContent = "Creating ZIP..."; btnZip.disabled = true;
fetch('/zip', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify({ files: processedFiles }) }) .then(response => response.json()) .then(data => { if (data.status === 'success') { window.location.href = `/download?path=${encodeURIComponent(data.zip_path)}`; btnZip.textContent = "⬇️ Download All as ZIP"; btnZip.disabled = false; } else { alert('Failed to create ZIP'); btnZip.textContent = "⬇️ Download All as ZIP"; btnZip.disabled = false; } }) .catch(error => { console.error('Error:', error); btnZip.textContent = "⬇️ Download All as ZIP"; btnZip.disabled = false; }); }</script>
</body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237import http.serverimport socketserverimport osimport sysimport shutilimport jsonimport urllib.parseimport subprocessimport tempfileimport timeimport zipfile
# ConfigurationPORT = int(os.environ.get("PORT", 8989))ROOT_DIR = os.path.dirname(os.path.abspath(__file__))BIN_DIR = os.path.join(ROOT_DIR, "bin")# Use system temp directory which is writable in cloud environmentsTEMP_DIR = tempfile.gettempdir()
# Check pngquantPNGQUANT_PATH = os.environ.get("PNGQUANT_PATH")if not PNGQUANT_PATH: local_bin = os.path.join(BIN_DIR, "pngquant") if os.path.exists(local_bin) and os.access(local_bin, os.X_OK): PNGQUANT_PATH = local_binif not PNGQUANT_PATH: PNGQUANT_PATH = shutil.which("pngquant")
# Check jpegoptimJPEGOPTIM_PATH = os.environ.get("JPEGOPTIM_PATH")if not JPEGOPTIM_PATH: local_bin = os.path.join(BIN_DIR, "jpegoptim") if os.path.exists(local_bin) and os.access(local_bin, os.X_OK): JPEGOPTIM_PATH = local_binif not JPEGOPTIM_PATH: JPEGOPTIM_PATH = shutil.which("jpegoptim")
class TinyHandler(http.server.SimpleHTTPRequestHandler): def do_GET(self): parsed_path = urllib.parse.urlparse(self.path) path = parsed_path.path query = urllib.parse.parse_qs(parsed_path.query)
if path == "/": self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() # Serve the HTML file html_path = os.path.join(ROOT_DIR, "index.html") if os.path.exists(html_path): with open(html_path, 'rb') as f: self.wfile.write(f.read()) else: self.wfile.write(b"Error: index.html not found") return elif path == "/download": file_path = query.get("path", [None])[0] if file_path and os.path.exists(file_path) and file_path.startswith(TEMP_DIR): filename = os.path.basename(file_path) # Remove timestamp prefix for download filename (out_12345_name.png -> name.png) # Format is: out_TIMESTAMP_original.png parts = filename.split('_', 2) if len(parts) >= 3: download_name = parts[2] else: download_name = filename
self.send_response(200) # Detect content type if download_name.lower().endswith(".zip"): self.send_header("Content-Type", "application/zip") else: self.send_header("Content-Type", "application/octet-stream") self.send_header("Content-Disposition", f'attachment; filename="{download_name}"') self.send_header("Content-Length", str(os.path.getsize(file_path))) self.end_headers() with open(file_path, 'rb') as f: shutil.copyfileobj(f, self.wfile) else: self.send_error(404, "File not found") return
# Default static files super().do_GET()
def do_POST(self): parsed_path = urllib.parse.urlparse(self.path) if parsed_path.path == "/zip": # Handle bulk zip creation content_length = int(self.headers.get('Content-Length', 0)) if content_length > 0: post_data = self.rfile.read(content_length) try: data = json.loads(post_data.decode('utf-8')) file_paths = data.get('files', []) if not file_paths: self.send_error(400, "No files provided") return
zip_filename = f"tiny_images_{int(time.time())}.zip" zip_path = os.path.join(TEMP_DIR, zip_filename) with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf: for file_path in file_paths: if os.path.exists(file_path) and file_path.startswith(TEMP_DIR): # Extract original name filename = os.path.basename(file_path) parts = filename.split('_', 2) if len(parts) >= 3: arcname = parts[2] else: arcname = filename zipf.write(file_path, arcname) self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(json.dumps({ "status": "success", "zip_path": zip_path }).encode()) except Exception as e: self.send_error(500, str(e)) return
if parsed_path.path == "/upload": query = urllib.parse.parse_qs(parsed_path.query) filename = query.get("filename", ["image.png"])[0] content_length = int(self.headers.get('Content-Length', 0)) if content_length > 0: # Save uploaded file input_path = os.path.join(TEMP_DIR, f"in_{int(time.time())}_{filename}") with open(input_path, 'wb') as f: f.write(self.rfile.read(content_length)) output_path = os.path.join(TEMP_DIR, f"out_{int(time.time())}_{filename}") is_png = filename.lower().endswith('.png') is_jpg = filename.lower().endswith(('.jpg', '.jpeg')) result_data = {} try: if is_png and PNGQUANT_PATH: cmd = [ PNGQUANT_PATH, "--force", "--quality", "65-80", "--output", output_path, "--skip-if-larger", "--strip", input_path ] process = subprocess.run(cmd, capture_output=True) if process.returncode == 0: # Success pass elif process.returncode in [98, 99]: # Skipped - copy input to output so we can download it shutil.copy2(input_path, output_path) else: raise Exception("PNG Engine error") elif is_jpg and JPEGOPTIM_PATH: # Copy first because jpegoptim modifies in-place or needs dest # We will use --dest option if available or just copy then optimize shutil.copy2(input_path, output_path) # jpegoptim --strip-all --all-progressive -m80 target cmd = [ JPEGOPTIM_PATH, "--strip-all", "--all-progressive", "--max=80", output_path ] process = subprocess.run(cmd, capture_output=True) if process.returncode != 0: raise Exception("JPG Engine error") else: # No engine found or unsupported format, just copy shutil.copy2(input_path, output_path)
original_size = os.path.getsize(input_path) new_size = os.path.getsize(output_path) result_data = { "status": "success", "original_size": original_size, "new_size": new_size, "path": output_path } except Exception as e: result_data = {"status": "error", "message": str(e)}
# Cleanup input try: os.remove(input_path) except: pass
self.send_response(200) self.send_header("Content-type", "application/json") self.end_headers() self.wfile.write(json.dumps(result_data).encode()) else: self.send_error(400, "No content") return
self.send_error(404)
def run(): print(f"🐼 TinyPNG Local Server starting at port {PORT}") if not PNGQUANT_PATH: print("⚠️ Warning: pngquant not found. PNG compression will be disabled.") if not JPEGOPTIM_PATH: print("⚠️ Warning: jpegoptim not found. JPG compression will be disabled.") with socketserver.TCPServer(("0.0.0.0", PORT), TinyHandler) as httpd: try: httpd.serve_forever() except KeyboardInterrupt: print("\nShutting down...")
if __name__ == "__main__": run()DockerfileAdded+20
index.htmlAdded+340
web_app.pyAdded+237