File size: 2,792 Bytes
8efda93
692fcc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1a80ff8
 
692fcc8
 
1a80ff8
 
692fcc8
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6954ea
692fcc8
 
f6954ea
692fcc8
 
f6954ea
692fcc8
 
2ddc663
692fcc8
 
 
 
 
 
 
 
1a80ff8
 
 
 
 
692fcc8
 
 
 
 
 
 
 
 
 
 
 
 
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
# competitor_analysis_api.py
from fastapi import FastAPI, HTTPException, Request
from starlette.middleware.cors import CORSMiddleware
import openai
import os
import requests

# Initialize FastAPI app
app = FastAPI()

# Allow CORS for Wix integration
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],  # Adjust if needed for security
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

# Load API Keys from Environment Variables
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
SECRET_API_KEY = os.getenv("SECRET_API_KEY")  # API key for Wix communication

if not OPENAI_API_KEY:
    raise ValueError("Missing OpenAI API Key. Set OPENAI_API_KEY in environment variables.")
if not SECRET_API_KEY:
    raise ValueError("Missing SECRET_API_KEY. Set SECRET_API_KEY in environment variables.")

# OpenAI Client Setup
openai.api_key = OPENAI_API_KEY

# Function to analyze a competitor's website
async def analyze_competitor(competitor_url: str, industry: str):
    """Analyzes a competitor's website and provides AI-driven insights."""
    prompt = f"""
    You are an expert in competitive business analysis.
    Analyze the website {competitor_url} and provide insights on:
    - Website strategy (SEO, structure, content focus)
    - Strengths & weaknesses in their online presence
    - Estimated market positioning compared to industry standards
    - Recommendations for a business competing in {industry}
    """
    
    try:
        response = openai.chat.completions.create(
            model="gpt-3.5-turbo-16k",
            messages=[
                {"role": "system", "content": "You are a competitive market analyst"},
                {"role": "user", "content": prompt}
            ],
            max_tokens=4096,
            temperature=0.7
        )
        return response.choices[0].message.content.strip()
    except Exception as e:
        return f"Error generating analysis: {str(e)}"

# API Endpoint for Competitor Analysis
@app.post("/api/competitor_analysis")
async def competitor_analysis(request: Request):
    """Endpoint to analyze competitor data."""
    data = await request.json()
    provided_key = data.get("api_key")
    
    if not provided_key or provided_key != SECRET_API_KEY:
        raise HTTPException(status_code=403, detail="Unauthorized: Invalid API key.")
    
    competitor_url = data.get("competitor_url")
    industry = data.get("industry", "General")
    
    if not competitor_url:
        raise HTTPException(status_code=400, detail="Competitor URL is required.")
    
    analysis = await analyze_competitor(competitor_url, industry)
    return {"competitor_analysis": analysis}

# Run API (for local testing)
if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=7860)