File size: 11,823 Bytes
d401095
 
332b875
d401095
 
 
 
 
 
 
 
 
 
 
332b875
 
 
 
 
 
 
d401095
 
 
332b875
 
 
 
 
 
 
 
 
 
 
 
 
d401095
 
 
 
332b875
 
 
 
d401095
 
 
332b875
 
d401095
332b875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d401095
332b875
d401095
 
 
332b875
 
 
 
d401095
 
332b875
 
d401095
332b875
 
d401095
 
332b875
 
d401095
332b875
 
 
 
 
 
 
d401095
332b875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d401095
 
 
 
 
332b875
d401095
 
332b875
 
 
 
 
 
 
 
 
 
 
 
 
 
d401095
332b875
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d401095
332b875
d401095
 
 
332b875
d401095
 
 
 
332b875
 
 
 
 
 
 
d401095
 
332b875
 
d401095
 
332b875
d401095
332b875
d401095
 
 
332b875
 
 
 
d401095
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8ada918
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
"""
Hugging Face Spaces Entry Point
Improved UI with better logging, status indicators, and results display.
"""

import gradio as gr
import os
import sys
from datetime import datetime
from workflow import create_workflow, run_workflow_step_1, resume_workflow

# Add current directory to path
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))

# Log file path
LOG_FILE = "app.log"

def clear_logs():
    """Clear the log file for a fresh start."""
    with open(LOG_FILE, "w") as f:
        f.write(f"===== New Session Started at {datetime.now()} =====\n")

def start_test(figma_key, figma_id, url, hf_token):
    """Start the test and stop at the breakpoint."""
    # Clear logs at start of new test
    clear_logs()
    
    print(f"\n{'='*60}")
    print(f"๐Ÿš€ STARTING NEW TEST")
    print(f"{'='*60}")
    print(f"โฐ Time: {datetime.now()}")
    print(f"๐ŸŒ Website URL: {url}")
    print(f"๐Ÿ“ Figma File ID: {figma_id}")
    print(f"๐Ÿ”‘ Figma API Key: {'โœ… Provided' if figma_key else 'โŒ Missing'}")
    print(f"๐Ÿค— HF Token: {'โœ… Provided - AI Analysis will be enhanced' if hf_token else 'โš ๏ธ Not provided - Using basic comparison only'}")
    print(f"{'='*60}\n")
    
    execution_id = f"exec_{datetime.now().strftime('%Y%m%d_%H%M%S')}"
    thread_id = f"thread_{execution_id}"
    
    try:
        print(f"๐Ÿงต Thread ID: {thread_id}")
        print(f"\n๐Ÿ“‹ STEP 1: Capturing Screenshots...")
        print(f"-" * 40)
        
        state_snapshot = run_workflow_step_1(figma_id, figma_key, url, execution_id, thread_id, hf_token)
        
        if not state_snapshot or not state_snapshot.values:
            print("โŒ ERROR: Workflow returned empty state.")
            return "โŒ Error: Workflow failed to start or returned empty state.", None, get_current_logs()

        # Get captured screenshots info
        figma_screenshots = state_snapshot.values.get("figma_screenshots", {})
        website_screenshots = state_snapshot.values.get("website_screenshots", {})
        
        print(f"\n{'='*60}")
        print(f"โœ… STEP 1 COMPLETE!")
        print(f"{'='*60}")
        print(f"๐Ÿ“ธ Figma Screenshots: {len(figma_screenshots)}")
        for viewport, path in figma_screenshots.items():
            print(f"   โ€ข {viewport}: {path}")
        print(f"๐Ÿ“ธ Website Screenshots: {len(website_screenshots)}")
        for viewport, path in website_screenshots.items():
            print(f"   โ€ข {viewport}: {path}")
        print(f"\n๐Ÿ‘‰ Click 'Step 2: Run AI Analysis' to compare images")
        print(f"{'='*60}\n")
        
        status = f"โœ… Step 1 Complete!\n"
        status += f"Thread ID: {thread_id}\n\n"
        status += f"๐Ÿ“ธ Screenshots Captured:\n"
        status += f"  โ€ข Figma: {len(figma_screenshots)} images\n"
        status += f"  โ€ข Website: {len(website_screenshots)} images\n\n"
        status += f"๐Ÿค— HF Token: {'Active' if hf_token else 'Not provided'}\n\n"
        status += f"๐Ÿ‘‰ Click 'Step 2' button to run AI analysis"
        
        return status, thread_id, get_current_logs()
        
    except Exception as e:
        import traceback
        error_msg = f"โŒ Error: {str(e)}"
        print(f"\n{'='*60}")
        print(f"โŒ ERROR OCCURRED")
        print(f"{'='*60}")
        print(error_msg)
        traceback.print_exc()
        print(f"{'='*60}\n")
        return error_msg, None, get_current_logs()


def continue_test(thread_id, hf_token):
    """Resume the test after human approval."""
    if not thread_id:
        print("โŒ ERROR: No active thread found. Please run Step 1 first.")
        return "โŒ No active thread found. Please run Step 1 first.", get_current_logs()
    
    print(f"\n{'='*60}")
    print(f"๐Ÿ” STEP 2: RUNNING AI ANALYSIS")
    print(f"{'='*60}")
    print(f"โฐ Time: {datetime.now()}")
    print(f"๐Ÿงต Thread ID: {thread_id}")
    print(f"๐Ÿค— HF Token: {'โœ… Using enhanced AI analysis' if hf_token else 'โš ๏ธ Using basic comparison'}")
    print(f"-" * 40)
    
    try:
        print("๐Ÿ”„ Resuming workflow...")
        state_snapshot = resume_workflow(thread_id, user_approval=True)
        
        if not state_snapshot:
            print("โŒ ERROR: Workflow failed to resume.")
            return "โŒ Workflow failed to resume. Try running Step 1 again.", get_current_logs()
        
        # Extract results
        score = state_snapshot.values.get("similarity_score", 0)
        differences = state_snapshot.values.get("visual_differences", [])
        hf_analysis = state_snapshot.values.get("hf_analysis", {})
        status = state_snapshot.values.get("status", "unknown")
        error_msg = state_snapshot.values.get("error_message", "")
        
        print(f"\n{'='*60}")
        print(f"๐Ÿ“Š ANALYSIS RESULTS")
        print(f"{'='*60}")
        print(f"๐Ÿ“ˆ Similarity Score: {score}/100")
        print(f"๐Ÿ” Differences Found: {len(differences)}")
        print(f"๐Ÿ“‹ Status: {status}")
        
        if error_msg:
            print(f"โš ๏ธ Error: {error_msg}")
        
        # Show difference details
        if differences:
            print(f"\n๐Ÿ“‹ DIFFERENCE DETAILS:")
            print(f"-" * 40)
            for i, diff in enumerate(differences, 1):
                if isinstance(diff, dict):
                    print(f"\n  [{i}] {diff.get('title', 'Unknown')}")
                    print(f"      Category: {diff.get('category', 'N/A')}")
                    print(f"      Severity: {diff.get('severity', 'N/A')}")
                    print(f"      Viewport: {diff.get('viewport', 'N/A')}")
                    if diff.get('description'):
                        print(f"      Description: {diff.get('description', '')[:100]}...")
        
        # Show HF Analysis results
        if hf_analysis:
            print(f"\n๐Ÿค— HF VISION ANALYSIS:")
            print(f"-" * 40)
            for viewport, analysis in hf_analysis.items():
                print(f"  {viewport.upper()}:")
                if isinstance(analysis, dict):
                    for key, value in analysis.items():
                        print(f"    โ€ข {key}: {str(value)[:100]}")
        
        print(f"\n{'='*60}")
        print(f"โœ… ANALYSIS COMPLETE!")
        print(f"{'='*60}\n")
        
        # Build result string for UI
        result = f"{'='*50}\n"
        result += f"๐Ÿ“Š ANALYSIS RESULTS\n"
        result += f"{'='*50}\n\n"
        result += f"๐Ÿ“ˆ Similarity Score: {score}/100\n"
        result += f"๐Ÿ” Differences Found: {len(differences)}\n"
        result += f"๐Ÿ“‹ Status: {status}\n\n"
        
        if differences:
            result += f"๐Ÿ“‹ DIFFERENCES:\n"
            result += f"-" * 30 + "\n"
            for i, diff in enumerate(differences[:10], 1):  # Show first 10
                if isinstance(diff, dict):
                    result += f"\n[{i}] {diff.get('title', 'Unknown')}\n"
                    result += f"    Severity: {diff.get('severity', 'N/A')}\n"
                    result += f"    Category: {diff.get('category', 'N/A')}\n"
            if len(differences) > 10:
                result += f"\n... and {len(differences) - 10} more differences\n"
        
        if hf_analysis:
            result += f"\n๐Ÿค— AI INSIGHTS:\n"
            result += f"-" * 30 + "\n"
            for viewport, analysis in hf_analysis.items():
                result += f"\n{viewport.upper()}:\n"
                if isinstance(analysis, dict):
                    for key, value in list(analysis.items())[:3]:
                        result += f"  โ€ข {key}: {str(value)[:80]}\n"
        
        return result, get_current_logs()
        
    except Exception as e:
        import traceback
        error_msg = f"โŒ Analysis Error: {str(e)}"
        print(f"\n{'='*60}")
        print(f"โŒ ERROR IN ANALYSIS")
        print(f"{'='*60}")
        print(error_msg)
        traceback.print_exc()
        print(f"{'='*60}\n")
        return error_msg, get_current_logs()


def get_current_logs():
    """Get current log contents."""
    try:
        with open(LOG_FILE, "r") as f:
            return f.read()
    except:
        return "No logs available yet."


# Gradio UI
def create_interface():
    with gr.Blocks(title="Advanced UI Regression Testing", theme=gr.themes.Soft()) as demo:
        gr.Markdown("# ๐Ÿš€ Advanced UI Regression Testing (LangGraph Powered)")
        gr.Markdown("Compare Figma designs with live websites to detect visual differences.")
        
        with gr.Row():
            # LEFT COLUMN - Inputs
            with gr.Column(scale=1):
                gr.Markdown("### ๐Ÿ“ Configuration")
                f_key = gr.Textbox(label="Figma API Key", type="password", placeholder="Enter your Figma API key")
                f_id = gr.Textbox(label="Figma File ID", placeholder="e.g., ENieX2p3Gy3TAtxaB36cZA")
                w_url = gr.Textbox(label="Website URL", placeholder="https://your-website.com")
                hf_token = gr.Textbox(label="Hugging Face API Token (Optional)", type="password", 
                                     placeholder="For enhanced AI analysis")
                
                gr.Markdown("### ๐ŸŽฎ Controls")
                start_btn = gr.Button("1๏ธโƒฃ Start Capture & Setup", variant="primary", size="lg")
                resume_btn = gr.Button("2๏ธโƒฃ Run AI Analysis", variant="secondary", size="lg")
                
                # Hidden state
                thread_id_state = gr.State()
        
            # RIGHT COLUMN - Results
            with gr.Column(scale=2):
                gr.Markdown("### ๐Ÿ“Š Status & Results")
                status_out = gr.Textbox(label="Current Status", lines=8, interactive=False)
                
                gr.Markdown("### ๐ŸŽฏ Final Analysis Results")
                final_out = gr.Textbox(label="Analysis Results", lines=12, interactive=False)
        
        # BOTTOM - Logs
        gr.Markdown("### ๐Ÿ“œ Execution Logs")
        gr.Markdown("*Logs refresh automatically every 2 seconds*")
        log_viewer = gr.Code(label="Live Logs", language="python", interactive=False, lines=20)
        refresh_logs = gr.Timer(value=2)
        
        # Clear button for logs
        clear_btn = gr.Button("๐Ÿ—‘๏ธ Clear Logs", variant="secondary", size="sm")

        # Event handlers
        start_btn.click(
            start_test, 
            inputs=[f_key, f_id, w_url, hf_token], 
            outputs=[status_out, thread_id_state, log_viewer]
        )
        
        resume_btn.click(
            continue_test,
            inputs=[thread_id_state, hf_token],
            outputs=[final_out, log_viewer]
        )
        
        clear_btn.click(
            lambda: (clear_logs(), "Logs cleared.", "", get_current_logs()),
            outputs=[status_out, final_out, log_viewer]
        )

        refresh_logs.tick(get_current_logs, outputs=[log_viewer])
        
    return demo


if __name__ == "__main__":
    # Setup logging to file
    class Logger(object):
        def __init__(self):
            self.terminal = sys.stdout
            # Clear log file on startup
            with open(LOG_FILE, "w") as f:
                f.write(f"===== Application Startup at {datetime.now()} =====\n\n")
            self.log = open(LOG_FILE, "a")

        def write(self, message):
            self.terminal.write(message)
            self.log.write(message)
            self.log.flush()

        def flush(self):
            self.terminal.flush()
            self.log.flush()

        def isatty(self):
            return hasattr(self.terminal, 'isatty') and self.terminal.isatty()

    sys.stdout = Logger()
    sys.stderr = Logger()
    
    print(f"--- Application Started at {datetime.now()} ---")
    demo = create_interface()
    demo.launch(server_name="0.0.0.0", server_port=7860)