File size: 2,212 Bytes
58e450d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db, save_post
from utils.preprocessing import preprocess_data
from utils.image_processing import extract_text_from_image, analyze_image
import joblib
import requests
from PIL import Image
from io import BytesIO
from textblob import TextBlob
import pandas as pd

# Load models
viral_model = joblib.load("models/viral_potential_model.pkl")
engagement_model = joblib.load("models/engagement_rate_model.pkl")
promotion_model = joblib.load("models/promotion_strategy_model.pkl")

router = APIRouter()

# Endpoint to analyze and save a post
@router.post("/analyze-post")
async def analyze_post(caption: str, hashtags: str, image_url: str, db: Session = Depends(get_db)):
    try:
        # Download and analyze the image
        response = requests.get(image_url)
        response.raise_for_status()
        image = Image.open(BytesIO(response.content))
        extracted_text = extract_text_from_image(image)
        image_analysis = analyze_image(image)

        # Preprocess input for models
        features = {
            'caption_length': len(caption),
            'hashtag_count': len(hashtags.split(",")),
            'sentiment': TextBlob(caption).sentiment.polarity
        }
        features_df = pd.DataFrame([features])

        # Make predictions
        viral_score = viral_model.predict_proba(features_df)[0][1]
        engagement_rate = engagement_model.predict(features_df)[0]
        promote = promotion_model.predict(features_df)[0]

        # Save post to database
        post_data = {
            "caption": caption,
            "hashtags": hashtags,
            "image_url": image_url,
            "engagement_rate": engagement_rate,
            "viral_score": viral_score,
            "promote": promote
        }
        save_post(db, post_data)

        return {
            "extracted_text": extracted_text,
            "image_analysis": image_analysis,
            "viral_score": viral_score,
            "engagement_rate": engagement_rate,
            "promote": bool(promote)
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))