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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c2e52aa
 
 
 
d90900e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
183cb98
d90900e
 
 
 
 
0def27e
d90900e
 
 
183cb98
d90900e
183cb98
d90900e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
import openai
import anthropic
import json
import os
from typing import Dict, Any

class SEOAgent:
    def __init__(self):
        self.seo_tasks = {
            "Keyword Research & Analysis": {
                "description": "Research short-tail and long-tail keywords with competition analysis",
                "prompt": """You are an expert SEO strategist with 15 years of experience. Your task is to conduct thorough keyword research.

CONTEXT: You must think in first principles - understanding user intent, search behaviour, and market dynamics.

TASK: Analyse the provided topic/industry and deliver actionable keyword insights.

METHODOLOGY:
1. Identify 10-15 high-value short-tail keywords (1-2 words)
2. Generate 20-30 long-tail keywords (3+ words) with commercial intent
3. Categorise keywords by search intent (informational, navigational, commercial, transactional)
4. Estimate search volumes and competition levels
5. Identify keyword gaps competitors might be missing

OUTPUT FORMAT:
- Primary Keywords (short-tail)
- Long-tail Opportunities
- Intent Classification
- Competition Analysis
- Content Gap Opportunities
- Recommended Focus Keywords (top 5 with rationale)

CONSTRAINTS:
- Use British English
- Be direct and actionable
- Consider second-order effects (how these keywords impact overall strategy)
- Think about third-order consequences (long-term brand positioning)

Industry/Topic: {user_input}"""
            },
            
            "Technical SEO Audit": {
                "description": "Detailed technical analysis and recommendations",
                "prompt": """You are a technical SEO specialist with deep expertise in website architecture and search engine mechanics.

FIRST PRINCIPLES THINKING: Search engines need to crawl, understand, and index content efficiently.

TASK: Conduct a thorough technical SEO analysis for the provided website.

AUDIT FRAMEWORK:
1. Site Architecture Assessment
   - URL structure evaluation
   - Internal linking analysis
   - Navigation hierarchy review

2. Technical Performance
   - Page speed factors
   - Core Web Vitals considerations
   - Mobile responsiveness issues

3. Indexation Analysis
   - Crawl accessibility
   - XML sitemap structure
   - Robots.txt configuration

4. On-page Technical Elements
   - Meta tag optimisation
   - Schema markup opportunities
   - Header tag hierarchy

SECOND-ORDER CONSIDERATIONS:
- How technical issues impact user experience
- Effect on conversion rates and business metrics

THIRD-ORDER CONSEQUENCES:
- Long-term search visibility implications
- Brand credibility and trust factors

OUTPUT STRUCTURE:
- Critical Issues (immediate fixes required)
- Moderate Priority Items
- Enhancement Opportunities
- Implementation Roadmap (30/60/90 days)

Website URL: {user_input}"""
            },
            
            "Content Strategy Development": {
                "description": "Create a detailed content strategies aligned with SEO goals",
                "prompt": """You are a content strategist who understands the intersection of user needs, search behaviour, and business objectives.

FIRST PRINCIPLES: Content must solve user problems whilst achieving business goals through search visibility.

OBJECTIVE: Develop a detailed content strategy for the specified industry/niche.

STRATEGIC FRAMEWORK:
1. Audience Analysis
   - Primary and secondary personas
   - Content consumption patterns
   - Pain points and information needs

2. Content Pillars
   - Core topic areas
   - Supporting subtopics
   - Content cluster strategy

3. Content Types & Formats
   - Blog posts, guides, resources
   - Video, infographic, interactive content
   - Gated vs. ungated content strategy

4. Editorial Calendar Planning
   - Publishing frequency recommendations
   - Seasonal content opportunities
   - Evergreen vs. trending content balance

SECOND-ORDER EFFECTS:
- How content supports different funnel stages
- Cross-promotional opportunities
- Social media amplification potential

THIRD-ORDER IMPLICATIONS:
- Brand authority building
- Industry thought leadership positioning
- Long-term organic traffic growth

DELIVERABLES:
- Content Pillar Framework
- 30 Content Ideas with SEO Focus
- Editorial Calendar Template
- Content Performance KPIs
- Resource Requirements

Industry/Business Focus: {user_input}"""
            },
            
            "Competitor SEO Analysis": {
                "description": "Analyse competitor strategies and identify opportunities",
                "prompt": """You are a competitive intelligence analyst specialising in SEO strategy evaluation.

ANALYTICAL APPROACH: Reverse-engineer successful competitor strategies whilst identifying market gaps.

MISSION: Conduct a detailed competitor analysis to uncover strategic opportunities.

ANALYSIS FRAMEWORK:
1. Competitor Identification
   - Direct competitors
   - Indirect/industry competitors
   - Aspirational competitors (different sectors, similar strategies)

2. Content Strategy Analysis
   - Top-performing content types
   - Content gap identification
   - Publishing patterns and frequency

3. Keyword Strategy Evaluation
   - Keyword overlap analysis
   - Competitor-unique keywords
   - Ranking position comparisons

4. Technical Strategy Assessment
   - Site architecture approaches
   - User experience patterns
   - Technical advantages/disadvantages

5. Link Building Strategy Review
   - Backlink profile analysis
   - Link acquisition patterns
   - Authority building approaches

SECOND-ORDER CONSIDERATIONS:
- Market positioning implications
- Resource allocation insights
- Timing and opportunity windows

THIRD-ORDER STRATEGY:
- Long-term competitive differentiation
- Market leadership positioning
- Industry disruption opportunities

OUTPUT STRUCTURE:
- Competitor Landscape Overview
- Strategic Strengths & Weaknesses
- Opportunity Matrix
- Recommended Actions (immediate, short-term, long-term)
- Competitive Differentiation Strategy

Competitor Domain(s) or Industry: {user_input}"""
            },
            
            "Link Building Strategy": {
                "description": "Develop detailed link acquisition strategies",
                "prompt": """You are a digital PR and link building expert with proven success in building high-authority backlink profiles.

CORE PRINCIPLE: Quality links come from creating genuine value and building authentic relationships.

OBJECTIVE: Design a detailed link building strategy for the specified website/industry.

STRATEGIC APPROACH:
1. Link Opportunity Audit
   - Industry-relevant websites
   - Competitor backlink analysis
   - Broken link opportunities
   - Resource page inclusions

2. Content-Led Link Building
   - Linkable asset creation
   - Digital PR campaign ideas
   - Industry research and surveys
   - Expert roundup opportunities

3. Relationship Building Framework
   - Industry influencer identification
   - Partnership opportunities
   - Guest posting prospects
   - Podcast appearance possibilities

4. Technical Link Strategies
   - Internal linking optimisation
   - Link reclamation opportunities
   - Brand mention conversion
   - Competitor link replication

SECOND-ORDER EFFECTS:
- Brand awareness and visibility
- Referral traffic generation
- Industry relationship development

THIRD-ORDER BENEFITS:
- Market authority establishment
- Long-term partnership development
- Crisis communication network

DELIVERABLES:
- Target Website List (50+ prospects)
- Outreach Email Templates
- Content Campaign Ideas
- Monthly Link Building Calendar
- Success Metrics and KPIs

Website/Industry: {user_input}"""
            },
            
            "Local SEO Optimisation": {
                "description": "Optimise for local search visibility and conversions",
                "prompt": """You are a local SEO specialist who understands how local businesses win in their geographic markets.

FUNDAMENTAL TRUTH: Local search success requires consistent NAP data, authentic reviews, and genuine community engagement.

TASK: Create a detailed local SEO strategy for the specified business.

OPTIMISATION FRAMEWORK:
1. Google Business Profile Excellence
   - Profile completion and optimisation
   - Category selection strategy
   - Photo and video content plan
   - Regular posting schedule

2. Local Citation Building
   - Core citation sources identification
   - Industry-specific directories
   - NAP consistency audit
   - Citation cleanup requirements

3. Review Management Strategy
   - Review acquisition campaigns
   - Response strategy for all reviews
   - Reputation monitoring system
   - Customer feedback integration

4. Local Content Strategy
   - Location-specific content creation
   - Community event participation
   - Local partnership opportunities
   - Geo-targeted keyword integration

5. Technical Local SEO
   - Schema markup implementation
   - Location page optimisation
   - Mobile-first considerations
   - Local link building

SECOND-ORDER IMPACT:
- Customer trust and credibility
- Foot traffic and phone call increases
- Local market dominance

LONG-TERM VISION:
- Community brand recognition
- Market leadership position
- Sustainable competitive advantage

OUTPUT:
- Local SEO Audit Results
- Google Business Profile Action Plan
- Citation Building Strategy
- Review Management System
- Local Content Calendar

Business Name/Location: {user_input}"""
            },
            
            "Performance Analysis & Reporting": {
                "description": "Analyse SEO performance and create actionable insights",
                "prompt": """You are a data analyst who transforms SEO metrics into business intelligence and strategic recommendations.

DATA PHILOSOPHY: Numbers tell stories, but insights drive decisions and business growth.

OBJECTIVE: Analyse SEO performance data and provide actionable strategic recommendations.

ANALYSIS FRAMEWORK:
1. Traffic & Ranking Analysis
   - Organic traffic trends
   - Keyword ranking movements
   - Click-through rate analysis
   - Impression and position data

2. Conversion & Business Impact
   - Goal completion analysis
   - Revenue attribution to organic search
   - Lead quality assessment
   - Customer lifetime value correlation

3. Technical Performance Review
   - Site speed impact on rankings
   - Core Web Vitals performance
   - Mobile usability metrics
   - Crawl error identification

4. Content Performance Evaluation
   - Top-performing content identification
   - Content gap analysis
   - User engagement metrics
   - Social sharing patterns

SECOND-ORDER INSIGHTS:
- User behaviour pattern recognition
- Seasonal trend identification
- Competitive position changes

STRATEGIC IMPLICATIONS:
- Resource allocation recommendations
- Priority setting for improvements
- ROI optimisation opportunities

REPORTING STRUCTURE:
- Executive Summary (key wins and challenges)
- Performance Metrics Dashboard
- Trend Analysis and Insights
- Recommended Actions with Timeline
- Projected Impact Assessment

Website/Data Period: {user_input}"""
            },
            
            "Site Architecture Planning": {
                "description": "Design optimal website structure for SEO and user experience",
                "prompt": """You are a website architect who designs structures that serve both users and search engines effectively.

ARCHITECTURAL PRINCIPLE: Great site structure makes information findable, understandable, and actionable.

CHALLENGE: Design optimal website architecture for the specified project requirements.

PLANNING FRAMEWORK:
1. Information Architecture Design
   - Content categorisation and hierarchy
   - User journey mapping
   - Navigation structure planning
   - URL structure strategy

2. SEO-Friendly Architecture
   - Internal linking strategy
   - Category and tag organisation
   - Breadcrumb navigation planning
   - XML sitemap structure

3. User Experience Integration
   - Mobile-first design considerations
   - Page load speed optimisation
   - Conversion path optimisation
   - Accessibility compliance

4. Technical Implementation
   - CMS structure recommendations
   - Database architecture considerations
   - Caching strategy integration
   - CDN implementation planning

SECOND-ORDER CONSIDERATIONS:
- Content scalability requirements
- Future expansion possibilities
- Integration with existing systems

LONG-TERM VISION:
- Sustainable growth accommodation
- Maintenance and update efficiency
- Competitive advantage creation

DELIVERABLES:
- Site Architecture Diagram
- URL Structure Guidelines
- Navigation Design Recommendations
- Internal Linking Strategy
- Technical Implementation Roadmap

Project Requirements: {user_input}"""
            }
        }

    def call_openai(self, api_key: str, prompt: str, user_input: str) -> str:
        try:
            client = openai.OpenAI(api_key=api_key)
            formatted_prompt = prompt.format(user_input=user_input)
            
            response = client.chat.completions.create(
                model="gpt-4.1",  # Latest GPT model
                messages=[
                    {"role": "system", "content": "You are an expert SEO professional. Follow the prompt instructions precisely. Use British English, be direct and actionable, think in first principles, and consider second and third-order consequences."},
                    {"role": "user", "content": formatted_prompt}
                ],
                max_tokens=2000,
                temperature=0.7
            )
            
            return response.choices[0].message.content
            
        except Exception as e:
            return f"OpenAI API Error: {str(e)}"

    def call_claude(self, api_key: str, prompt: str, user_input: str) -> str:
        try:
            client = anthropic.Anthropic(api_key=api_key)
            formatted_prompt = prompt.format(user_input=user_input)
            
            message = client.messages.create(
                model="claude-sonnet-4-20250514",  # Latest Claude model
                max_tokens=2000,
                temperature=0.7,
                system="You are an expert SEO professional. Follow the prompt instructions precisely. Use British English, be direct and actionable, think in first principles, and consider second and third-order consequences.",
                messages=[
                    {
                        "role": "user",
                        "content": formatted_prompt
                    }
                ]
            )
            
            return message.content[0].text
            
        except Exception as e:
            return f"Claude API Error: {str(e)}"

def create_interface():
    seo_agent = SEOAgent()
    
    def process_seo_task(openai_key, claude_key, selected_task, user_input, selected_model):
        if not user_input.strip():
            return "❌ **Error**: Please provide input for your SEO task."
        
        if not openai_key.strip() and not claude_key.strip():
            return "❌ **Error**: Please provide at least one API key (OpenAI or Claude)."
        
        if selected_task not in seo_agent.seo_tasks:
            return "❌ **Error**: Invalid task selection."
        
        task_info = seo_agent.seo_tasks[selected_task]
        prompt = task_info["prompt"]
        
        # Format the output header
        result = f"""# πŸš€ SEO Agent Results
        
## Task: {selected_task}
**Model Used**: {selected_model}
**Input**: {user_input[:100]}{"..." if len(user_input) > 100 else ""}

---

"""
        
        try:
            if selected_model == "OpenAI GPT-4.1" and openai_key.strip():
                ai_response = seo_agent.call_openai(openai_key, prompt, user_input)
            elif selected_model == "Claude 4 Sonnet" and claude_key.strip():
                ai_response = seo_agent.call_claude(claude_key, prompt, user_input)
            else:
                return "❌ **Error**: Selected model requires corresponding API key."
            
            result += ai_response
            
        except Exception as e:
            result += f"❌ **Processing Error**: {str(e)}"
        
        return result
    
    # Create Gradio interface
    with gr.Blocks(
        title="SEO Agent - Professional SEO Analysis Tool",
        theme=gr.themes.Soft(),
        css="""
        .gradio-container {
            max-width: 1200px !important;
        }
        .task-description {
            background: #f8f9fa;
            border-left: 4px solid #007bff;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
            color: #000000 !important;
        }
        .task-description * {
            color: #000000 !important;
        }
        """
    ) as demo:
        
        gr.Markdown("""
        # 🎯 SEO Agent - Professional SEO Analysis Tool
        
        **Transform your SEO strategy with AI-powered insights**
        
        This tool provides expert-level SEO analysis across eight core areas professional SEO executives handle daily. Each task uses carefully crafted prompts designed to produce optimal results.
        
        ---
        """)
        
        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("## πŸ”‘ API Configuration")
                openai_key = gr.Textbox(
                    label="OpenAI API Key",
                    type="password",
                    placeholder="sk-proj-...",
                    info="Required for GPT-4.1 analysis"
                )
                claude_key = gr.Textbox(
                    label="Claude API Key", 
                    type="password",
                    placeholder="sk-ant-...",
                    info="Required for Claude 4 Sonnet analysis"
                )
                
                selected_model = gr.Radio(
                    choices=["OpenAI GPT-4.1", "Claude 4 Sonnet"],
                    label="Select AI Model",
                    value="OpenAI GPT-4.1",
                    info="Choose your preferred AI model"
                )
                
            with gr.Column(scale=2):
                gr.Markdown("## πŸ“‹ SEO Task Selection")
                
                task_choices = list(seo_agent.seo_tasks.keys())
                selected_task = gr.Dropdown(
                    choices=task_choices,
                    label="Select SEO Task",
                    value=task_choices[0],
                    info="Choose the SEO analysis you need"
                )
                
                # Dynamic task description
                task_description = gr.Markdown(
                    value=f"**{seo_agent.seo_tasks[task_choices[0]]['description']}**",
                    elem_classes=["task-description"]
                )
                
                def update_task_description(task):
                    return f"**{seo_agent.seo_tasks[task]['description']}**"
                
                selected_task.change(
                    fn=update_task_description,
                    inputs=[selected_task],
                    outputs=[task_description]
                )
        
        with gr.Row():
            with gr.Column():
                user_input = gr.Textbox(
                    label="Your Input",
                    placeholder="Enter your website URL, industry, topic, or specific requirements...",
                    lines=4,
                    info="Provide relevant details for your selected SEO task"
                )
                
                analyze_btn = gr.Button(
                    "πŸ” Analyse",
                    variant="primary",
                    size="lg"
                )
        
        with gr.Row():
            with gr.Column():
                output = gr.Markdown(
                    label="SEO Analysis Results",
                    value="Results will appear here after analysis...",
                    height=600
                )
        
        # Button click handler
        analyze_btn.click(
            fn=process_seo_task,
            inputs=[openai_key, claude_key, selected_task, user_input, selected_model],
            outputs=[output]
        )
        
        gr.Markdown("""
        ---
        
        ## 🎯 Available SEO Tasks
        
        1. **Keyword Research & Analysis** - Detailed keyword strategy development
        2. **Technical SEO Audit** - Complete technical analysis and recommendations  
        3. **Content Strategy Development** - Strategic content planning aligned with SEO goals
        4. **Competitor SEO Analysis** - Competitive intelligence and opportunity identification
        5. **Link Building Strategy** - Authority-building link acquisition strategies
        6. **Local SEO Optimisation** - Local search visibility and conversion optimisation
        7. **Performance Analysis & Reporting** - Data-driven insights and strategic recommendations
        8. **Site Architecture Planning** - Optimal website structure for SEO and UX
        
        **Note**: This tool requires either an OpenAI or Claude API key. Results are generated in real-time and formatted for immediate use in your SEO strategy.
        """)
    
    return demo

if __name__ == "__main__":
    demo = create_interface()
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
        share=True
    )