File size: 29,585 Bytes
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba7275
ebdc441
 
 
 
cba7275
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
cba7275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba7275
ebdc441
 
 
 
 
 
 
cba7275
 
ebdc441
 
cba7275
 
 
 
 
 
 
 
 
 
 
 
ebdc441
cba7275
 
 
 
ebdc441
 
 
cba7275
 
 
 
ebdc441
cba7275
 
ebdc441
 
 
 
 
cba7275
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
cba7275
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba7275
ebdc441
 
 
 
 
 
 
 
cba7275
ebdc441
 
 
 
 
cba7275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
cba7275
ebdc441
 
cba7275
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cba7275
ebdc441
 
 
 
 
 
 
 
 
cba7275
 
 
 
 
 
ebdc441
cba7275
ebdc441
 
 
 
 
 
 
cba7275
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3d5ba52
 
 
 
 
 
 
 
ebdc441
3d5ba52
ebdc441
 
 
 
 
 
 
 
3d5ba52
ebdc441
 
 
 
 
3d5ba52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
3d5ba52
 
 
 
 
 
ebdc441
 
3d5ba52
 
 
 
 
 
ebdc441
 
3d5ba52
 
 
 
 
 
ebdc441
 
3d5ba52
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ebdc441
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
"""
Web Testing Suite for Hugging Face Spaces
Interactive UI with Gradio for Performance, SEO, Security, Accessibility Testing
"""

import gradio as gr
import time
import ssl
import socket
import json
import requests
from urllib.parse import urljoin, urlparse
from bs4 import BeautifulSoup
from datetime import datetime
import re
from typing import Dict, List, Tuple

# ============================================================================
# PERFORMANCE TESTING
# ============================================================================

class PerformanceTester:
    def __init__(self, url: str):
        self.url = url
    
    def measure_ttfb(self) -> float:
        try:
            start = time.time()
            response = requests.get(self.url, stream=True, timeout=10)
            ttfb = time.time() - start
            return round(ttfb * 1000, 2)
        except Exception as e:
            return f"Error: {e}"
    
    def get_payload_size(self) -> Dict:
        try:
            response = requests.get(self.url, timeout=10)
            html_size = len(response.content)
            
            soup = BeautifulSoup(response.content, 'html.parser')
            
            scripts = len(soup.find_all('script', src=True))
            stylesheets = len(soup.find_all('link', rel='stylesheet'))
            images = len(soup.find_all('img'))
            
            return {
                'html_size_kb': round(html_size / 1024, 2),
                'script_count': scripts,
                'stylesheet_count': stylesheets,
                'image_count': images,
                'compression': response.headers.get('Content-Encoding', 'none')
            }
        except Exception as e:
            return {'error': str(e)}
    
    def test_all(self) -> str:
        result = f"⚑ **PERFORMANCE TEST RESULTS**\n\n"
        result += f"🌐 URL: {self.url}\n\n"
        recommendations = []
        
        # TTFB
        ttfb = self.measure_ttfb()
        if isinstance(ttfb, float):
            if ttfb < 200:
                status = "βœ… Excellent"
            elif ttfb < 500:
                status = "⚠️ Needs Improvement"
                recommendations.append("πŸ”§ **TTFB Issue:** Reduce server response time by:\n   β€’ Using a CDN\n   β€’ Optimizing database queries\n   β€’ Enabling caching\n   β€’ Upgrading server resources")
            else:
                status = "❌ Poor"
                recommendations.append("🚨 **Critical TTFB Issue:** Immediate action required:\n   β€’ Check server health and resources\n   β€’ Implement Redis/Memcached caching\n   β€’ Use a CDN (Cloudflare, AWS CloudFront)\n   β€’ Optimize backend code\n   β€’ Consider server upgrade")
            result += f"⏱️ **Time To First Byte:** {ttfb} ms {status}\n"
        else:
            result += f"⏱️ **Time To First Byte:** {ttfb}\n"
        
        # Payload
        payload = self.get_payload_size()
        if 'error' not in payload:
            result += f"\nπŸ“¦ **Page Size:** {payload['html_size_kb']} KB"
            if payload['html_size_kb'] > 1000:
                result += " ❌"
                recommendations.append("🚨 **Large Page Size:** Reduce HTML size:\n   β€’ Minify HTML, CSS, and JavaScript\n   β€’ Remove unused code\n   β€’ Compress images\n   β€’ Implement lazy loading")
            elif payload['html_size_kb'] > 500:
                result += " ⚠️"
                recommendations.append("πŸ”§ **Page Size Warning:** Consider:\n   β€’ Enabling Gzip/Brotli compression\n   β€’ Minifying resources\n   β€’ Optimizing images")
            else:
                result += " βœ…"
            
            result += f"\nπŸ“œ **Scripts:** {payload['script_count']}"
            if payload['script_count'] > 20:
                result += " ⚠️"
                recommendations.append("πŸ”§ **Too Many Scripts:** Reduce JavaScript files:\n   β€’ Bundle scripts together\n   β€’ Remove unused libraries\n   β€’ Use async/defer attributes\n   β€’ Implement code splitting")
            
            result += f"\n🎨 **Stylesheets:** {payload['stylesheet_count']}"
            if payload['stylesheet_count'] > 10:
                result += " ⚠️"
                recommendations.append("πŸ”§ **Too Many Stylesheets:** Optimize CSS:\n   β€’ Combine CSS files\n   β€’ Remove unused styles\n   β€’ Use CSS minification\n   β€’ Consider critical CSS approach")
            
            result += f"\nπŸ–ΌοΈ **Images:** {payload['image_count']}"
            result += f"\nπŸ—œοΈ **Compression:** {payload['compression']}"
            if payload['compression'] == 'none':
                result += " ❌"
                recommendations.append("🚨 **No Compression:** Enable compression:\n   β€’ Add Gzip/Brotli to server config\n   β€’ For Apache: Enable mod_deflate\n   β€’ For Nginx: Add gzip on;\n   β€’ For Node.js: Use compression middleware")
        
        # Add recommendations section
        if recommendations:
            result += f"\n\n{'='*50}\n"
            result += f"πŸ’‘ **RECOMMENDATIONS**\n\n"
            result += "\n\n".join(recommendations)
        
        return result


# ============================================================================
# SEO AUDITOR
# ============================================================================

class SEOAuditor:
    def __init__(self, url: str):
        self.url = url
        self.soup = None
    
    def fetch_page(self):
        try:
            response = requests.get(self.url, timeout=10)
            self.soup = BeautifulSoup(response.content, 'html.parser')
        except Exception as e:
            return False
        return True
    
    def check_meta_tags(self) -> Dict:
        title = self.soup.find('title')
        description = self.soup.find('meta', attrs={'name': 'description'})
        og_title = self.soup.find('meta', property='og:title')
        og_description = self.soup.find('meta', property='og:description')
        og_image = self.soup.find('meta', property='og:image')
        canonical = self.soup.find('link', rel='canonical')
        
        return {
            'title': title.text if title else '❌ Missing',
            'title_length': len(title.text) if title else 0,
            'description': description.get('content')[:100] + '...' if description else '❌ Missing',
            'og_title': 'βœ… Present' if og_title else '❌ Missing',
            'og_description': 'βœ… Present' if og_description else '❌ Missing',
            'og_image': 'βœ… Present' if og_image else '❌ Missing',
            'canonical': 'βœ… Present' if canonical else '❌ Missing'
        }
    
    def check_headers(self) -> Dict:
        h1 = self.soup.find_all('h1')
        h2 = self.soup.find_all('h2')
        h3 = self.soup.find_all('h3')
        
        return {
            'h1_count': len(h1),
            'h1_text': [h.text.strip()[:50] for h in h1][:3],
            'h2_count': len(h2),
            'h3_count': len(h3),
            'valid': len(h1) == 1
        }
    
    def check_sitemap(self) -> Dict:
        sitemap_url = urljoin(self.url, '/sitemap.xml')
        try:
            resp = requests.get(sitemap_url, timeout=5)
            return {'exists': resp.status_code == 200}
        except:
            return {'exists': False}
    
    def audit(self) -> str:
        result = f"πŸ” **SEO AUDIT RESULTS**\n\n"
        result += f"🌐 URL: {self.url}\n\n"
        recommendations = []
        
        if not self.fetch_page():
            return result + "❌ Failed to fetch page"
        
        # Meta Tags
        meta = self.check_meta_tags()
        result += f"πŸ“ **Meta Tags**\n"
        
        # Title
        result += f"β€’ Title: {meta['title']}\n"
        result += f"β€’ Title Length: {meta['title_length']} chars "
        if 50 <= meta['title_length'] <= 60:
            result += f"βœ…\n"
        else:
            result += f"⚠️\n"
            if meta['title'] == '❌ Missing':
                recommendations.append("🚨 **Missing Title Tag:**\n   β€’ Add <title>Your Page Title</title> in <head>\n   β€’ Keep it 50-60 characters\n   β€’ Include primary keyword\n   β€’ Make it unique for each page")
            elif meta['title_length'] < 50:
                recommendations.append("πŸ”§ **Title Too Short:**\n   β€’ Expand to 50-60 characters\n   β€’ Add descriptive keywords\n   β€’ Include brand name")
            elif meta['title_length'] > 60:
                recommendations.append("πŸ”§ **Title Too Long:**\n   β€’ Shorten to 50-60 characters\n   β€’ Google truncates at ~60 chars\n   β€’ Keep most important words first")
        
        # Description
        result += f"β€’ Description: {meta['description']}\n"
        if meta['description'] == '❌ Missing':
            recommendations.append("🚨 **Missing Meta Description:**\n   β€’ Add <meta name=\"description\" content=\"...\">\n   β€’ Keep it 150-160 characters\n   β€’ Include target keywords naturally\n   β€’ Make it compelling for click-through")
        
        # Open Graph
        result += f"β€’ OG Title: {meta['og_title']}\n"
        result += f"β€’ OG Description: {meta['og_description']}\n"
        result += f"β€’ OG Image: {meta['og_image']}\n"
        if meta['og_title'] == '❌ Missing' or meta['og_description'] == '❌ Missing' or meta['og_image'] == '❌ Missing':
            recommendations.append("⚠️ **Missing Open Graph Tags:**\n   β€’ Add <meta property=\"og:title\" content=\"...\">\n   β€’ Add <meta property=\"og:description\" content=\"...\">\n   β€’ Add <meta property=\"og:image\" content=\"...\">\n   β€’ Improves social media sharing appearance")
        
        # Canonical
        result += f"β€’ Canonical: {meta['canonical']}\n\n"
        if meta['canonical'] == '❌ Missing':
            recommendations.append("⚠️ **Missing Canonical Tag:**\n   β€’ Add <link rel=\"canonical\" href=\"...\">\n   β€’ Prevents duplicate content issues\n   β€’ Points to preferred URL version")
        
        # Headers
        headers = self.check_headers()
        result += f"πŸ“‹ **Header Structure**\n"
        result += f"β€’ H1 Count: {headers['h1_count']} {'βœ…' if headers['valid'] else '❌'}\n"
        if not headers['valid']:
            if headers['h1_count'] == 0:
                recommendations.append("🚨 **Missing H1 Tag:**\n   β€’ Add exactly ONE <h1> tag per page\n   β€’ Should describe main page content\n   β€’ Include primary keyword\n   β€’ Must be unique on page")
            elif headers['h1_count'] > 1:
                recommendations.append("❌ **Multiple H1 Tags:**\n   β€’ Use only ONE <h1> per page\n   β€’ Convert extra H1s to <h2> or <h3>\n   β€’ Maintains proper heading hierarchy\n   β€’ Better for SEO and accessibility")
        
        if headers['h1_text']:
            result += f"β€’ H1 Text: {headers['h1_text'][0]}\n"
        result += f"β€’ H2 Count: {headers['h2_count']}\n"
        result += f"β€’ H3 Count: {headers['h3_count']}\n\n"
        
        # Sitemap
        sitemap = self.check_sitemap()
        result += f"πŸ—ΊοΈ **Sitemap:** {'βœ… Found' if sitemap['exists'] else '❌ Not Found'}\n"
        if not sitemap['exists']:
            recommendations.append("❌ **Missing Sitemap:**\n   β€’ Create sitemap.xml file\n   β€’ List all important pages\n   β€’ Submit to Google Search Console\n   β€’ Update when adding new pages\n   β€’ Use sitemap generator tools")
        
        # Add recommendations
        if recommendations:
            result += f"\n{'='*50}\n"
            result += f"πŸ’‘ **SEO RECOMMENDATIONS**\n\n"
            result += "\n\n".join(recommendations)
        
        return result


# ============================================================================
# SECURITY TESTER
# ============================================================================

class SecurityTester:
    def __init__(self, url: str):
        self.url = url
        self.domain = urlparse(url).netloc
    
    def check_ssl(self) -> Dict:
        try:
            context = ssl.create_default_context()
            with socket.create_connection((self.domain, 443), timeout=5) as sock:
                with context.wrap_socket(sock, server_hostname=self.domain) as ssock:
                    cert = ssock.getpeercert()
                    return {
                        'valid': True,
                        'expires': cert['notAfter']
                    }
        except Exception as e:
            return {'valid': False, 'error': str(e)}
    
    def check_security_headers(self) -> Dict:
        try:
            response = requests.get(self.url, timeout=10)
            headers = response.headers
            
            return {
                'hsts': headers.get('Strict-Transport-Security', '❌'),
                'x_content_type': headers.get('X-Content-Type-Options', '❌'),
                'x_frame': headers.get('X-Frame-Options', '❌'),
                'csp': headers.get('Content-Security-Policy', '❌'),
                'referrer': headers.get('Referrer-Policy', '❌')
            }
        except Exception as e:
            return {'error': str(e)}
    
    def check_mixed_content(self) -> List[str]:
        if not self.url.startswith('https'):
            return ['⚠️ Page is not HTTPS']
        
        try:
            response = requests.get(self.url, timeout=10)
            soup = BeautifulSoup(response.content, 'html.parser')
            mixed = []
            
            for tag in soup.find_all(['img', 'script', 'link']):
                src = tag.get('src') or tag.get('href', '')
                if src.startswith('http://'):
                    mixed.append(src[:50])
            
            return mixed[:5] if mixed else ['βœ… No mixed content']
        except:
            return ['Error checking']
    
    def test_all(self) -> str:
        result = f"πŸ”’ **SECURITY TEST RESULTS**\n\n"
        result += f"🌐 URL: {self.url}\n\n"
        recommendations = []
        
        # SSL
        ssl_info = self.check_ssl()
        if ssl_info['valid']:
            result += f"πŸ” **SSL Certificate:** βœ… Valid\n"
            result += f"β€’ Expires: {ssl_info['expires']}\n\n"
        else:
            result += f"πŸ” **SSL Certificate:** ❌ Invalid\n\n"
            recommendations.append("🚨 **SSL Certificate Issue:**\n   β€’ Install valid SSL certificate\n   β€’ Use Let's Encrypt (free)\n   β€’ Or purchase from trusted CA\n   β€’ Configure HTTPS redirect\n   β€’ Update all internal links to HTTPS")
        
        # Security Headers
        headers = self.check_security_headers()
        if 'error' not in headers:
            result += f"πŸ›‘οΈ **Security Headers**\n"
            
            # HSTS
            hsts_present = headers['hsts'] != '❌'
            result += f"β€’ HSTS: {'βœ…' if hsts_present else '❌'}\n"
            if not hsts_present:
                recommendations.append("❌ **Missing HSTS Header:**\n   β€’ Add: Strict-Transport-Security: max-age=31536000\n   β€’ Forces HTTPS connections\n   β€’ Prevents protocol downgrade attacks\n   β€’ Apache: Header always set Strict-Transport-Security \"max-age=31536000\"\n   β€’ Nginx: add_header Strict-Transport-Security \"max-age=31536000\";")
            
            # X-Content-Type-Options
            xct_present = headers['x_content_type'] != '❌'
            result += f"β€’ X-Content-Type-Options: {'βœ…' if xct_present else '❌'}\n"
            if not xct_present:
                recommendations.append("❌ **Missing X-Content-Type-Options:**\n   β€’ Add: X-Content-Type-Options: nosniff\n   β€’ Prevents MIME type sniffing\n   β€’ Reduces XSS attack vectors\n   β€’ Apache: Header set X-Content-Type-Options \"nosniff\"\n   β€’ Nginx: add_header X-Content-Type-Options \"nosniff\";")
            
            # X-Frame-Options
            xfo_present = headers['x_frame'] != '❌'
            result += f"β€’ X-Frame-Options: {'βœ…' if xfo_present else '❌'}\n"
            if not xfo_present:
                recommendations.append("❌ **Missing X-Frame-Options:**\n   β€’ Add: X-Frame-Options: SAMEORIGIN\n   β€’ Prevents clickjacking attacks\n   β€’ Blocks iframe embedding by other sites\n   β€’ Apache: Header always set X-Frame-Options \"SAMEORIGIN\"\n   β€’ Nginx: add_header X-Frame-Options \"SAMEORIGIN\";")
            
            # CSP
            csp_present = headers['csp'] != '❌'
            result += f"β€’ Content-Security-Policy: {'βœ…' if csp_present else '❌'}\n"
            if not csp_present:
                recommendations.append("⚠️ **Missing Content-Security-Policy:**\n   β€’ Add CSP header to prevent XSS\n   β€’ Example: Content-Security-Policy: default-src 'self'\n   β€’ Restricts resource loading sources\n   β€’ Start with report-only mode\n   β€’ Use CSP evaluator tools to test")
            
            # Referrer Policy
            ref_present = headers['referrer'] != '❌'
            result += f"β€’ Referrer-Policy: {'βœ…' if ref_present else '❌'}\n\n"
            if not ref_present:
                recommendations.append("⚠️ **Missing Referrer-Policy:**\n   β€’ Add: Referrer-Policy: strict-origin-when-cross-origin\n   β€’ Controls referrer information\n   β€’ Protects user privacy\n   β€’ Apache: Header set Referrer-Policy \"strict-origin-when-cross-origin\"\n   β€’ Nginx: add_header Referrer-Policy \"strict-origin-when-cross-origin\";")
        
        # Mixed Content
        mixed = self.check_mixed_content()
        result += f"πŸ“¦ **Mixed Content Check**\n"
        has_mixed = False
        for item in mixed:
            result += f"β€’ {item}\n"
            if item.startswith('http://'):
                has_mixed = True
        
        if has_mixed:
            recommendations.append("❌ **Mixed Content Detected:**\n   β€’ Change all HTTP resources to HTTPS\n   β€’ Update image sources\n   β€’ Update script/stylesheet URLs\n   β€’ Check third-party integrations\n   β€’ Use protocol-relative URLs: //example.com")
        
        # Add recommendations
        if recommendations:
            result += f"\n{'='*50}\n"
            result += f"πŸ’‘ **SECURITY RECOMMENDATIONS**\n\n"
            result += "\n\n".join(recommendations)
        
        return result


# ============================================================================
# ACCESSIBILITY TESTER
# ============================================================================

class AccessibilityTester:
    def __init__(self, url: str):
        self.url = url
        self.soup = None
    
    def fetch_page(self):
        try:
            response = requests.get(self.url, timeout=10)
            self.soup = BeautifulSoup(response.content, 'html.parser')
            return True
        except:
            return False
    
    def check_alt_attributes(self) -> Dict:
        images = self.soup.find_all('img')
        missing_alt = []
        
        for img in images:
            if not img.get('alt'):
                src = img.get('src', 'No src')[:50]
                missing_alt.append(src)
        
        return {
            'total': len(images),
            'missing': len(missing_alt),
            'samples': missing_alt[:5]
        }
    
    def check_form_labels(self) -> Dict:
        inputs = self.soup.find_all(['input', 'textarea', 'select'])
        missing_labels = 0
        
        for inp in inputs:
            input_id = inp.get('id')
            aria_label = inp.get('aria-label')
            
            if input_id:
                label = self.soup.find('label', attrs={'for': input_id})
                if not label and not aria_label:
                    missing_labels += 1
            elif not aria_label:
                missing_labels += 1
        
        return {
            'total': len(inputs),
            'missing': missing_labels
        }
    
    def test_all(self) -> str:
        result = f"β™Ώ **ACCESSIBILITY TEST RESULTS**\n\n"
        result += f"🌐 URL: {self.url}\n\n"
        recommendations = []
        
        if not self.fetch_page():
            return result + "❌ Failed to fetch page"
        
        # Alt Attributes
        alt_check = self.check_alt_attributes()
        result += f"πŸ–ΌοΈ **Image Alt Attributes**\n"
        result += f"β€’ Total Images: {alt_check['total']}\n"
        result += f"β€’ Missing Alt: {alt_check['missing']} "
        if alt_check['missing'] == 0:
            result += f"βœ…\n"
        else:
            result += f"❌\n"
            recommendations.append(f"❌ **Missing Alt Attributes ({alt_check['missing']} images):**\n   β€’ Add descriptive alt text to all images\n   β€’ Example: <img src=\"photo.jpg\" alt=\"Person coding on laptop\">\n   β€’ Describe image content clearly\n   β€’ Use empty alt=\"\" for decorative images\n   β€’ Improves screen reader experience\n   β€’ Benefits SEO")
        
        if alt_check['samples']:
            result += f"β€’ Sample Missing Alt: {', '.join(alt_check['samples'][:2])}\n"
        result += f"\n"
        
        # Form Labels
        label_check = self.check_form_labels()
        result += f"πŸ“ **Form Labels**\n"
        result += f"β€’ Total Inputs: {label_check['total']}\n"
        result += f"β€’ Missing Labels: {label_check['missing']} "
        if label_check['missing'] == 0:
            result += f"βœ…\n"
        else:
            result += f"❌\n"
            recommendations.append(f"❌ **Missing Form Labels ({label_check['missing']} inputs):**\n   β€’ Add <label> for each input field\n   β€’ Example: <label for=\"email\">Email:</label>\n   β€’ Or use aria-label attribute\n   β€’ Example: <input aria-label=\"Search\">\n   β€’ Helps users understand form purpose\n   β€’ Required for WCAG compliance\n   β€’ Improves mobile usability")
        
        # Add recommendations
        if recommendations:
            result += f"\n{'='*50}\n"
            result += f"πŸ’‘ **ACCESSIBILITY RECOMMENDATIONS**\n\n"
            result += "\n\n".join(recommendations)
            result += f"\n\n{'='*50}\n"
            result += f"πŸ“š **Additional Resources:**\n"
            result += f"β€’ WCAG Guidelines: https://www.w3.org/WAI/WCAG21/quickref/\n"
            result += f"β€’ WebAIM: https://webaim.org/\n"
            result += f"β€’ A11Y Project: https://www.a11yproject.com/\n"
        
        return result


# ============================================================================
# GRADIO INTERFACE
# ============================================================================

def run_performance_test(url):
    if not url:
        return "⚠️ Please enter a URL"
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    try:
        tester = PerformanceTester(url)
        return tester.test_all()
    except Exception as e:
        return f"❌ Error: {str(e)}"

def run_seo_audit(url):
    if not url:
        return "⚠️ Please enter a URL"
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    try:
        auditor = SEOAuditor(url)
        return auditor.audit()
    except Exception as e:
        return f"❌ Error: {str(e)}"

def run_security_test(url):
    if not url:
        return "⚠️ Please enter a URL"
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    try:
        tester = SecurityTester(url)
        return tester.test_all()
    except Exception as e:
        return f"❌ Error: {str(e)}"

def run_accessibility_test(url):
    if not url:
        return "⚠️ Please enter a URL"
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    try:
        tester = AccessibilityTester(url)
        return tester.test_all()
    except Exception as e:
        return f"❌ Error: {str(e)}"

def run_all_tests(url):
    if not url:
        return "⚠️ Please enter a URL", "", "", ""
    if not url.startswith(('http://', 'https://')):
        url = 'https://' + url
    
    perf = run_performance_test(url)
    seo = run_seo_audit(url)
    sec = run_security_test(url)
    a11y = run_accessibility_test(url)
    
    return perf, seo, sec, a11y

# Custom CSS for scrollable textboxes
custom_css = """
.scrollable-textbox textarea {
    max-height: 400px !important;
    overflow-y: auto !important;
}
"""

# Create Gradio Interface
with gr.Blocks(title="Web Testing Suite", theme=gr.themes.Soft(), css=custom_css) as demo:
    gr.Markdown("""
    # πŸš€ Comprehensive Web Testing Suite
    Test any website for **Performance**, **SEO**, **Security**, and **Accessibility**
    """)
    
    with gr.Row():
        url_input = gr.Textbox(
            label="🌐 Website URL",
            placeholder="https://example.com or example.com",
            scale=3
        )
    
    with gr.Row():
        test_all_btn = gr.Button("πŸ” Run All Tests", variant="primary", scale=1)
        guideline_btn = gr.Button("πŸ“– Show Guidelines", variant="secondary", scale=1)
    
    # Guidelines Accordion
    with gr.Accordion("πŸ“‹ Testing Guidelines & Features", open=False, visible=False) as guidelines_section:
        gr.Markdown("""
        ## πŸ“¦ What's Included

        ### 1. ⚑ Performance Tester
        - **TTFB** (Time To First Byte)
        - Full page load metrics with Selenium
        - DNS, TCP, and response time measurements
        - Payload size analysis (HTML, CSS, JS, images)
        - Resource count tracking
        - Lighthouse integration for Core Web Vitals (FCP, LCP, CLS, TTI)

        ### 2. πŸ” SEO Auditor
        - Meta tag validation (title, description, OG tags)
        - Title/description length optimization checks
        - Header structure analysis (H1-H3)
        - Broken internal link detection
        - Sitemap.xml verification
        - JSON-LD schema extraction

        ### 3. πŸ”’ Security Tester
        - SSL certificate validation & expiry check
        - Security headers audit (CSP, HSTS, X-Frame-Options, etc.)
        - Mixed content detection (HTTP on HTTPS pages)
        - Basic XSS vulnerability testing
        - CORS configuration analysis

        ### 4. β™Ώ Accessibility Tester
        - Missing alt attribute detection
        - ARIA role validation
        - Form label checking
        - Keyboard focus/tabindex analysis
        - WCAG compliance indicators

        ### 5. πŸ€– E2E Tester (Selenium)
        - Login flow automation
        - Form submission testing
        - Button click interactions
        - Screenshot capture
        - Performance tracing
        - Custom test suite runner

        ---

        ## πŸ’‘ How to Use
        1. Enter your website URL (with or without https://)
        2. Click **"Run All Tests"** for comprehensive analysis
        3. Or click individual test buttons for specific checks
        4. View detailed results in each tab
        5. Results are scrollable for long outputs

        ## 🎯 Best Practices
        - Test after major updates
        - Regular security audits recommended
        - Fix accessibility issues for better UX
        - Monitor performance metrics monthly
        - Keep SEO elements updated
        """)
    
    with gr.Row():
        perf_btn = gr.Button("⚑ Performance", scale=1)
        seo_btn = gr.Button("πŸ” SEO", scale=1)
        sec_btn = gr.Button("πŸ”’ Security", scale=1)
        a11y_btn = gr.Button("β™Ώ Accessibility", scale=1)
    
    with gr.Tabs():
        with gr.Tab("⚑ Performance"):
            perf_output = gr.Textbox(
                label="Performance Test Results", 
                lines=20,
                max_lines=20,
                elem_classes=["scrollable-textbox"]
            )
        
        with gr.Tab("πŸ” SEO"):
            seo_output = gr.Textbox(
                label="SEO Audit Results", 
                lines=20,
                max_lines=20,
                elem_classes=["scrollable-textbox"]
            )
        
        with gr.Tab("πŸ”’ Security"):
            sec_output = gr.Textbox(
                label="Security Test Results", 
                lines=20,
                max_lines=20,
                elem_classes=["scrollable-textbox"]
            )
        
        with gr.Tab("β™Ώ Accessibility"):
            a11y_output = gr.Textbox(
                label="Accessibility Test Results", 
                lines=20,
                max_lines=20,
                elem_classes=["scrollable-textbox"]
            )
    
    gr.Markdown("""
    ---
    ### πŸ“Š Quick Reference
    - βœ… **Green**: Passed / Optimal
    - ⚠️ **Yellow**: Needs Attention
    - ❌ **Red**: Failed / Critical Issue
    
    *Results are automatically scrollable when content exceeds the display area*
    """)
    
    # Toggle guidelines visibility
    def toggle_guidelines():
        return gr.Accordion(visible=True, open=True)
    
    guideline_btn.click(
        toggle_guidelines,
        outputs=[guidelines_section]
    )
    
    # Button actions
    test_all_btn.click(
        run_all_tests,
        inputs=[url_input],
        outputs=[perf_output, seo_output, sec_output, a11y_output]
    )
    
    perf_btn.click(run_performance_test, inputs=[url_input], outputs=[perf_output])
    seo_btn.click(run_seo_audit, inputs=[url_input], outputs=[seo_output])
    sec_btn.click(run_security_test, inputs=[url_input], outputs=[sec_output])
    a11y_btn.click(run_accessibility_test, inputs=[url_input], outputs=[a11y_output])

if __name__ == "__main__":
    demo.launch()