Spaces:
Sleeping

File size: 9,809 Bytes
93f7b1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
54f9644
 
 
93f7b1e
 
 
 
 
54f9644
 
 
93f7b1e
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
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()