import http.server import socketserver import os import sys import shutil import json import urllib.parse import subprocess import tempfile import time import zipfile # Configuration PORT = 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 environments TEMP_DIR = tempfile.gettempdir() # Check pngquant PNGQUANT_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_bin if not PNGQUANT_PATH: PNGQUANT_PATH = shutil.which("pngquant") # Check jpegoptim JPEGOPTIM_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_bin if 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}") # Allow address reuse to prevent "Address already in use" errors on restart socketserver.TCPServer.allow_reuse_address = True 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.") # Ensure logs are flushed immediately sys.stdout.flush() with socketserver.TCPServer(("0.0.0.0", PORT), TinyHandler) as httpd: try: httpd.serve_forever() except KeyboardInterrupt: print("\nShutting down...") if __name__ == "__main__": run()