File size: 9,778 Bytes
d59f3c4
882d716
 
ccbc0a0
 
d59f3c4
 
 
2d074f9
882d716
ccbc0a0
 
 
 
 
 
eae91d6
ccbc0a0
d59f3c4
eae91d6
ccbc0a0
d59f3c4
ccbc0a0
d59f3c4
 
 
 
 
ccbc0a0
 
 
 
eae91d6
 
 
 
 
 
 
 
 
 
 
ccbc0a0
 
 
 
 
eae91d6
ccbc0a0
 
 
d59f3c4
 
 
 
 
 
 
 
 
ccbc0a0
d59f3c4
 
 
eae91d6
d59f3c4
 
 
eae91d6
d59f3c4
 
 
ccbc0a0
 
 
 
 
 
a753f35
eae91d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d59f3c4
eae91d6
 
 
 
 
 
 
d59f3c4
eae91d6
 
d59f3c4
eae91d6
 
 
d59f3c4
eae91d6
 
 
 
 
 
 
 
 
 
 
d59f3c4
eae91d6
 
d59f3c4
eae91d6
 
 
 
d59f3c4
eae91d6
 
 
d59f3c4
eae91d6
 
 
 
d59f3c4
eae91d6
d59f3c4
eae91d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d59f3c4
 
eae91d6
d59f3c4
 
 
 
2bf5132
ccbc0a0
 
d59f3c4
ccbc0a0
d59f3c4
 
ccbc0a0
 
 
 
 
eae91d6
d59f3c4
ccbc0a0
d59f3c4
 
eae91d6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ccbc0a0
eae91d6
d59f3c4
ccbc0a0
eae91d6
 
 
d59f3c4
eae91d6
 
d59f3c4
2bf5132
ccbc0a0
eae91d6
ccbc0a0
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
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
from flask import Flask, request, render_template_string
from PIL import Image
import numpy as np
import io
import base64
import torch
import torchvision.transforms as transforms
import os
import sys

app = Flask(__name__)

HTML_TEMPLATE = """
<!DOCTYPE html>
<html>
<head>
    <title>ZeroIG Enhancement - Debug</title>
    <style>
        body { font-family: Arial, sans-serif; max-width: 1000px; margin: 0 auto; padding: 20px; }
        .debug { background: #f0f0f0; padding: 15px; margin: 10px 0; border-radius: 5px; font-family: monospace; }
        .container { text-align: center; }
        .upload-area { border: 2px dashed #ccc; padding: 40px; margin: 20px 0; border-radius: 10px; }
        .result { margin-top: 20px; }
        .comparison { display: flex; justify-content: space-around; flex-wrap: wrap; }
        .image-container { margin: 10px; }
        img { max-width: 400px; height: auto; border: 1px solid #ddd; border-radius: 5px; }
        .status { color: green; font-weight: bold; margin: 10px 0; }
        .error { color: red; }
    </style>
</head>
<body>
    <div class="container">
        <h1>πŸ”§ ZeroIG Debug Mode</h1>
        
        <div class="debug">
            <h3>πŸ“ File Check:</h3>
            {{ file_status }}
        </div>
        
        <div class="debug">
            <h3>🐍 Import Status:</h3>
            {{ import_status }}
        </div>
        
        <form method="post" enctype="multipart/form-data">
            <div class="upload-area">
                <input type="file" name="image" accept="image/*" required>
                <br><br>
                <button type="submit" style="padding: 10px 20px; font-size: 16px;">πŸ§ͺ Test Enhancement</button>
            </div>
        </form>
        
        {% if status %}
        <div class="status">{{ status }}</div>
        {% endif %}
        
        {% if error %}
        <div class="error">{{ error }}</div>
        {% endif %}
        
        {% if original_image and result_image %}
        <div class="result">
            <h3>Results:</h3>
            <div class="comparison">
                <div class="image-container">
                    <h4>Original</h4>
                    <img src="data:image/png;base64,{{ original_image }}" alt="Original">
                </div>
                <div class="image-container">
                    <h4>Enhanced</h4>
                    <img src="data:image/png;base64,{{ result_image }}" alt="Enhanced">
                </div>
            </div>
        </div>
        {% endif %}
    </div>
</body>
</html>
"""

def check_files():
    """Check what files are available"""
    status = []
    
    # Check current directory files
    files_in_dir = os.listdir('.')
    status.append(f"Files in current directory: {files_in_dir}")
    
    # Check specific ZeroIG files
    required_files = ['model.py', 'loss.py', 'utils.py']
    for file in required_files:
        if os.path.exists(file):
            status.append(f"βœ… {file} - EXISTS")
            # Check file size
            size = os.path.getsize(file)
            status.append(f"   Size: {size} bytes")
        else:
            status.append(f"❌ {file} - MISSING")
    
    # Check weights directory
    if os.path.exists('weights'):
        weights_files = os.listdir('weights')
        status.append(f"πŸ“ weights/ directory: {weights_files}")
    else:
        status.append("πŸ“ weights/ directory: NOT FOUND")
    
    return "<br>".join(status)

def check_imports():
    """Try importing ZeroIG modules and report results"""
    status = []
    
    try:
        # Add current directory to path
        import sys
        sys.path.insert(0, '.')
        status.append("βœ… Added current directory to Python path")
        
        # Try importing each module
        try:
            import model
            status.append("βœ… Successfully imported 'model' module")
            
            # Check what's in the model module
            model_contents = dir(model)
            status.append(f"   model module contents: {model_contents}")
            
            # Try to access specific classes
            if hasattr(model, 'Network'):
                status.append("βœ… Found Network class")
            else:
                status.append("❌ Network class not found")
                
            if hasattr(model, 'Finetunemodel'):
                status.append("βœ… Found Finetunemodel class")
            else:
                status.append("❌ Finetunemodel class not found")
                
        except Exception as e:
            status.append(f"❌ Failed to import model: {e}")
        
        try:
            import loss
            status.append("βœ… Successfully imported 'loss' module")
        except Exception as e:
            status.append(f"❌ Failed to import loss: {e}")
            
        try:
            import utils
            status.append("βœ… Successfully imported 'utils' module")
        except Exception as e:
            status.append(f"❌ Failed to import utils: {e}")
            
    except Exception as e:
        status.append(f"❌ General import error: {e}")
    
    return "<br>".join(status)

def try_create_model():
    """Try to create ZeroIG model and report what happens"""
    try:
        sys.path.insert(0, '.')
        
        from model import Network, Finetunemodel
        
        # Try creating Network
        network = Network()
        print("βœ… Successfully created Network model")
        
        # Try creating Finetunemodel (this will fail without weights, but should show the error)
        try:
            finetuned = Finetunemodel("./weights/model.pt")
            print("βœ… Successfully created Finetunemodel")
            return finetuned, "Finetunemodel"
        except Exception as e:
            print(f"⚠️ Finetunemodel failed (expected without weights): {e}")
            print("βœ… Using Network model instead")
            return network, "Network"
            
    except Exception as e:
        print(f"❌ Model creation failed: {e}")
        import traceback
        traceback.print_exc()
        return None, f"Failed: {e}"

# Try to load model on startup
print("πŸš€ Starting ZeroIG debug app...")
print("πŸ“ Checking files...")
file_check = check_files()
print("🐍 Checking imports...")
import_check = check_imports()

# Try to create model
print("πŸ€– Trying to create model...")
model, model_status = try_create_model()

def simple_enhance(image):
    """Fallback enhancement"""
    arr = np.array(image).astype(np.float32)
    enhanced = np.clip(arr * 1.5, 0, 255).astype(np.uint8)
    return Image.fromarray(enhanced)

def image_to_base64(image):
    """Convert PIL image to base64"""
    img_buffer = io.BytesIO()
    image.save(img_buffer, format='PNG')
    img_str = base64.b64encode(img_buffer.getvalue()).decode()
    return img_str

@app.route('/', methods=['GET', 'POST'])
def index():
    original_image = None
    result_image = None
    status = None
    error = None
    
    if request.method == 'POST':
        try:
            file = request.files['image']
            if file:
                print(f"Processing: {file.filename}")
                
                image = Image.open(file.stream).convert('RGB')
                original_image = image_to_base64(image)
                
                if model is not None:
                    # Try using the actual model
                    try:
                        device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
                        model.to(device)
                        model.eval()
                        
                        transform = transforms.ToTensor()
                        input_tensor = transform(image).unsqueeze(0).to(device)
                        
                        with torch.no_grad():
                            if hasattr(model, 'enhance') and hasattr(model, 'denoise_1'):
                                enhanced, denoised = model(input_tensor)
                                result_tensor = denoised
                            else:
                                outputs = model(input_tensor)
                                result_tensor = outputs[13]
                        
                        result_tensor = result_tensor.squeeze(0).cpu().clamp(0, 1)
                        enhanced_image = transforms.ToPILImage()(result_tensor)
                        result_image = image_to_base64(enhanced_image)
                        status = f"βœ… Used {model_status} model successfully!"
                        
                    except Exception as e:
                        print(f"Model processing error: {e}")
                        enhanced_image = simple_enhance(image)
                        result_image = image_to_base64(enhanced_image)
                        status = f"⚠️ Model failed, used simple enhancement: {e}"
                else:
                    enhanced_image = simple_enhance(image)
                    result_image = image_to_base64(enhanced_image)
                    status = "⚠️ No model available, used simple enhancement"
                    
        except Exception as e:
            error = f"Error: {e}"
            print(f"Error: {e}")
    
    return render_template_string(HTML_TEMPLATE,
                                  file_status=file_check,
                                  import_status=import_check,
                                  original_image=original_image,
                                  result_image=result_image,
                                  status=status,
                                  error=error)

if __name__ == '__main__':
    print("πŸš€ Debug app ready!")
    app.run(host='0.0.0.0', port=7860)