Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
142 changes: 142 additions & 0 deletions complete_workflow_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""
Complete workflow test: Simulate frontend generating image and syncing to backend
"""

import requests
import json
from datetime import datetime, timezone

def simulate_complete_workflow():
"""Simulate the complete frontend workflow"""

print("🧪 Testing Complete Image Generation → Reports Workflow")
print("=" * 60)

# Step 1: Simulate frontend creating ImageResult after generation
print("📷 Step 1: Simulating frontend image generation result...")

# This simulates what the frontend does after receiving a successful generation response
frontend_image_result = {
"id": f"frontend_sim_{datetime.now().timestamp()}",
"url": "http://localhost:5001/api/images/DreamLayer_00029_.png",
"prompt": "debug test image for reports workflow",
"negativePrompt": "blurry, low quality",
"timestamp": int(datetime.now().timestamp() * 1000), # Frontend uses milliseconds
"settings": {
"model_name": "v15PrunedEmaonly_v15PrunedEmaonly.safetensors",
"sampler_name": "euler",
"steps": 10,
"cfg_scale": 7.0,
"width": 256,
"height": 256,
"seed": 987654321,
"batch_size": 1,
"negative_prompt": "blurry, low quality"
}
}

print(f"✅ Created frontend image result: {frontend_image_result['id']}")

# Step 2: Simulate frontend syncing gallery data to backend (auto-sync)
print("\n🔄 Step 2: Simulating frontend auto-sync to backend...")

gallery_data = {
"txt2img": [frontend_image_result],
"img2img": []
}

try:
response = requests.post(
'http://localhost:5002/api/gallery-data',
json=gallery_data,
headers={'Content-Type': 'application/json'}
)

if response.status_code == 200:
result = response.json()
print(f"✅ Gallery sync successful: {result}")
else:
print(f"❌ Gallery sync failed: {response.status_code} - {response.text}")
return False

except Exception as e:
print(f"❌ Gallery sync error: {e}")
return False

# Step 3: Test Reports tab behavior (what happens when user clicks Reports)
print("\n📋 Step 3: Testing Reports tab functionality...")

# The Reports tab should now show 1 image and allow report generation
try:
response = requests.post(
'http://localhost:5002/api/reports/generate',
json={'filename': 'complete_workflow_test.zip'},
headers={'Content-Type': 'application/json'}
)

if response.status_code == 200:
result = response.json()
print("✅ Report generation successful!")
print(f" Total images: {result.get('total_images')}")
print(f" Generation types: {result.get('generation_types')}")
print(f" CSV valid: {result.get('csv_validation', {}).get('valid')}")
print(f" Paths valid: {result.get('path_validation', {}).get('valid')}")
print(f" Bundle size: {result.get('bundle_size_bytes')} bytes")

# Step 4: Test download
print("\n📥 Step 4: Testing report download...")
download_response = requests.get(f"http://localhost:5002/api/reports/download/{result.get('report_filename')}")

if download_response.status_code == 200:
print(f"✅ Download successful: {len(download_response.content)} bytes")
return True
else:
print(f"❌ Download failed: {download_response.status_code}")
return False

else:
print(f"❌ Report generation failed: {response.status_code} - {response.text}")
return False

except Exception as e:
print(f"❌ Report generation error: {e}")
return False

def test_backend_state():
"""Check current backend state"""
print("\n🔍 Checking backend state...")

# Check if temp_gallery_data.json exists
try:
with open('/Users/Ayushi/Desktop/DreamLayer/DreamLayer/dream_layer_backend/temp_gallery_data.json', 'r') as f:
data = json.load(f)
print(f"📁 Backend has gallery data: {len(data.get('txt2img', []))} txt2img, {len(data.get('img2img', []))} img2img")
except FileNotFoundError:
print("📁 No temp_gallery_data.json found")

# Check served images
import os
served_dir = '/Users/Ayushi/Desktop/DreamLayer/DreamLayer/dream_layer_backend/served_images'
if os.path.exists(served_dir):
images = [f for f in os.listdir(served_dir) if f.endswith('.png')]
print(f"🖼️ Served images directory has: {len(images)} images")
if images:
print(f" Latest: {max(images)}")
else:
print("🖼️ No served_images directory found")

def main():
# First check backend state
test_backend_state()

# Then run complete workflow test
if simulate_complete_workflow():
print("\n🎉 COMPLETE WORKFLOW TEST PASSED!")
print("The Reports tab should now work correctly in the frontend.")
else:
print("\n❌ WORKFLOW TEST FAILED!")
print("There are still issues with the integration.")

if __name__ == "__main__":
main()
119 changes: 119 additions & 0 deletions debug_frontend_state.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,119 @@
<!DOCTYPE html>
<html>
<head>
<title>Frontend State Debug</title>
<style>
body { font-family: monospace; margin: 20px; }
.section { margin: 20px 0; padding: 10px; border: 1px solid #ccc; }
.button { padding: 10px; margin: 5px; background: #007bff; color: white; border: none; cursor: pointer; }
pre { background: #f8f9fa; padding: 10px; overflow: auto; }
</style>
</head>
<body>
<h1>DreamLayer Frontend State Debug</h1>

<div class="section">
<h2>Test Gallery Data Sync</h2>
<button class="button" onclick="testGallerySync()">Test Gallery Sync</button>
<button class="button" onclick="testReportGeneration()">Test Report Generation</button>
<button class="button" onclick="checkBackendState()">Check Backend State</button>
<pre id="results"></pre>
</div>

<script>
const log = (message) => {
const results = document.getElementById('results');
results.textContent += new Date().toISOString() + ': ' + message + '\n';
console.log(message);
};

async function testGallerySync() {
log('🔄 Testing gallery data sync...');

const testData = {
txt2img: [
{
id: `debug_test_${Date.now()}`,
url: "http://localhost:5001/api/images/test.png",
prompt: "debug test image",
negativePrompt: "blurry",
timestamp: Date.now(),
settings: {
model_name: "v15PrunedEmaonly_v15PrunedEmaonly.safetensors",
sampler_name: "euler",
steps: 15,
cfg_scale: 7.0,
width: 512,
height: 512,
seed: 123456,
batch_size: 1
}
}
],
img2img: []
};

try {
const response = await fetch('http://localhost:5002/api/gallery-data', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(testData)
});

const result = await response.json();
log(`✅ Gallery sync result: ${JSON.stringify(result)}`);
return true;
} catch (error) {
log(`❌ Gallery sync failed: ${error.message}`);
return false;
}
}

async function testReportGeneration() {
log('📋 Testing report generation...');

try {
const response = await fetch('http://localhost:5002/api/reports/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: 'debug_test.zip' })
});

const result = await response.json();
log(`📊 Report result: ${JSON.stringify(result, null, 2)}`);
} catch (error) {
log(`❌ Report generation failed: ${error.message}`);
}
}

async function checkBackendState() {
log('🔍 Checking backend state...');

try {
// Check if temp_gallery_data.json exists via a test API call
const response = await fetch('http://localhost:5002/api/reports/generate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ filename: 'state_check.zip' })
});

if (response.ok) {
const result = await response.json();
log(`📁 Backend has ${result.total_images} images`);
log(`📋 Generation types: ${result.generation_types?.join(', ')}`);
} else {
log(`❌ Backend check failed: ${response.status} ${response.statusText}`);
}
} catch (error) {
log(`❌ Backend check error: ${error.message}`);
}
}

// Auto-run diagnostics
window.onload = () => {
log('🚀 Starting automatic diagnostics...');
setTimeout(checkBackendState, 1000);
};
</script>
</body>
</html>
Loading