# index.py from fastapi import FastAPI, HTTPException from pydantic import BaseModel import openai import requests # Initialize the FastAPI app app = FastAPI() # OpenAI API key (replace with your own key) openai.api_key = "your_openai_api_key" # Unsplash API key (replace with your own key) UNSPLASH_API_KEY = "your_unsplash_api_key" # Request body schema class ArticleRequest(BaseModel): topic: str keywords: list[str] tone: str audience: str word_count: int @app.post("/generate-article") async def generate_article(request: ArticleRequest): """ Generate an SEO-optimized article based on user input with plagiarism checking. """ try: # Prepare GPT prompt prompt = ( f"Write a {request.word_count}-word article on the topic '{request.topic}'. " f"Include the following keywords: {', '.join(request.keywords)}. " f"The tone should be {request.tone}, and the article should be tailored for a {request.audience} audience." ) # Generate text using GPT response = openai.Completion.create( engine="text-davinci-003", prompt=prompt, max_tokens=request.word_count, temperature=0.7 ) article_text = response.choices[0].text.strip() # Check for plagiarism plagiarism_report = check_plagiarism(article_text) if plagiarism_report["plagiarism_detected"]: raise HTTPException(status_code=400, detail="Plagiarism detected in the generated article.") # Fetch relevant images from Unsplash image_url = fetch_image(request.topic) return { "article": article_text, "image": image_url, "plagiarism_report": plagiarism_report } except Exception as e: raise HTTPException(status_code=500, detail=str(e)) def fetch_image(query: str) -> str: """ Fetch a relevant image URL from Unsplash. """ try: url = f"https://api.unsplash.com/photos/random?query={query}&client_id={UNSPLASH_API_KEY}" response = requests.get(url) if response.status_code == 200: data = response.json() return data["urls"]["regular"] # Return the regular-sized image URL else: raise Exception("Failed to fetch image from Unsplash.") except Exception as e: raise HTTPException(status_code=500, detail=str(e)) def check_plagiarism(text: str) -> dict: """ Simulate a plagiarism check. In production, replace this with a real plagiarism-checking API. """ # Simulated plagiarism checking (always returns no plagiarism for now) return { "plagiarism_detected": False, "similarity_percentage": 0, # Percentage of detected similarity "originality_score": 100 # Higher score = more original }

Comments

Popular posts from this blog