Spaces:
Sleeping
Sleeping
| # 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 | |
| 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) |