|
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 |
|
|
|
|
|
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() |
|
|
|
|
|
@router.post("/analyze-post") |
|
async def analyze_post(caption: str, hashtags: str, image_url: str, db: Session = Depends(get_db)): |
|
try: |
|
|
|
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) |
|
|
|
|
|
features = { |
|
'caption_length': len(caption), |
|
'hashtag_count': len(hashtags.split(",")), |
|
'sentiment': TextBlob(caption).sentiment.polarity |
|
} |
|
features_df = pd.DataFrame([features]) |
|
|
|
|
|
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] |
|
|
|
|
|
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)) |