import os import sys import joblib import pandas as pd import json import re import uuid from huggingface_hub import hf_hub_download from fastapi import FastAPI, HTTPException, Depends, BackgroundTasks from supabase import Client from pydantic import BaseModel, Field from pydantic.config import ConfigDict from typing import List, Optional, Any, Dict import traceback from llama_cpp import Llama from statsmodels.tsa.api import Holt from dateutil.relativedelta import relativedelta from sklearn.preprocessing import LabelEncoder from core.support_agent import SupportAgent from core.strategist import AIStrategist from core.predictor import rank_influencers_by_match from core.utils import get_supabase_client from core.anomaly_detector import find_anomalies from core.matcher import rank_documents_by_similarity from core.utils import get_supabase_client, extract_colors_from_url from core.document_parser import parse_pdf_from_url from core.creative_chat import CreativeDirector from core.matcher import load_embedding_model try: from core.rag.store import VectorStore from core.inference.cache import cached_response except ImportError: VectorStore = None def cached_response(func): return func # --- Constants --- ROOT_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) MODELS_DIR = os.path.join(ROOT_DIR, 'models') # āœ… FIX: Swapped to a smaller, memory-friendly model to avoid crashing on free tier MODEL_REPO = "TheBloke/phi-2-GGUF" MODEL_FILENAME = "phi-2.Q2_K.gguf" # <-- This is a very small, low-quality version that fits in memory MODEL_SAVE_DIRECTORY = os.path.join(os.environ.get("WRITABLE_DIR", "/data"), "llm_model") LLAMA_MODEL_PATH = os.path.join(MODEL_SAVE_DIRECTORY, MODEL_FILENAME) EMBEDDING_MODEL_PATH = os.path.join(ROOT_DIR, 'embedding_model') DB_PATH = os.path.join(os.environ.get("WRITABLE_DIR", "/tmp"), "vector_db_persistent") # --- Global Instances --- _llm_instance: Optional[Llama] = None _vector_store: Optional[Any] = None _ai_strategist: Optional[AIStrategist] = None _creative_director: CreativeDirector | None = None _support_agent: Optional[SupportAgent] = None _budget_predictor = None _influencer_matcher = None _performance_predictor = None _payout_forecaster = None _earnings_optimizer = None _earnings_encoder = None _likes_predictor = None _comments_predictor = None _revenue_forecaster = None _performance_scorer = None def to_snake(name: str) -> str: return re.sub(r'(? dict: """A robust helper to clean common messy JSON outputs from smaller LLMs.""" cleaned = { "wins": [], "challenges": [], "opportunities": [], "sentiment": "Mixed" } # Default to Mixed # Clean list-based fields for key in ["wins", "challenges", "opportunities"]: if key in data and isinstance(data[key], list): for item in data[key]: if isinstance(item, str) and item: # Check if string is not empty cleaned[key].append(item.strip()) elif isinstance(item, dict) and 'text' in item and isinstance(item['text'], str) and item['text']: cleaned[key].append(item['text'].strip()) # Clean sentiment field sentiment_data = data.get("sentiment") if isinstance(sentiment_data, str) and sentiment_data: # Sometimes model sends "Positive." with a period, strip it. cleaned["sentiment"] = sentiment_data.strip().replace('.', '') elif isinstance(sentiment_data, dict): if sentiment_data.get('positive'): cleaned["sentiment"] = "Positive" elif sentiment_data.get('negative'): cleaned["sentiment"] = "Negative" else: cleaned["sentiment"] = "Mixed" return cleaned def process_summary_in_background(checkin_id: int, raw_text: str): """ This is the long-running background task. This version has the final, official prompt format for the Phi-2 model. """ print(f" - āš™ļø BACKGROUND JOB STARTED for check-in ID: {checkin_id}") # Each background task needs its own Supabase client. supabase = get_supabase_client() if not _llm_instance: print(f" - āŒ JOB FAILED ({checkin_id}): LLM instance was not available during background task.") supabase.table("influencer_weekly_checkins").update({ "status": "failed", "error_message": "AI model was not loaded." }).eq("id", checkin_id).execute() return # --- THE OFFICIAL & FINAL PROMPT FOR PHI-2 --- # This format is what the model is trained to understand. # It's direct, simple, and gives the instruction *after* the text. final_prompt = f'''Text: """{raw_text}""" Instruct: Analyze the text above and extract key points into a single, valid JSON object with the keys "wins", "challenges", "opportunities", and "sentiment". - "wins" should contain 1-2 positive sentences. - "challenges" should contain 1-2 negative sentences. - "opportunities" should contain 1-2 new ideas. - DO NOT repeat sentences across categories. - "sentiment" must be ONE word: "Positive", "Negative", or "Mixed". Your entire response must ONLY be the JSON object, starting with {{ and ending with }}. Output: ''' try: # Call the pre-loaded Llama instance output = _llm_instance( final_prompt, max_tokens=1024, temperature=0.0, top_p=0.95, top_k=40, repeat_penalty=1.1, stop=["Instruct:", "Text:", "Output:"], # Strict stop tokens matching the prompt echo=False ) # Get the raw text from the model's response raw_response_text = output['choices'][0]['text'].strip() print(f" - šŸ¤– JOB ({checkin_id}): Official Phi-2 Raw Response:\n---\n{raw_response_text}\n---") # The robust JSON parser json_match = re.search(r'\{.*\}', raw_response_text, re.DOTALL) if not json_match: raise ValueError("No valid JSON object found in the LLM's response. The model may have returned plain text.") # Extract the JSON string and parse it clean_json_text = json_match.group(0) summary_data_raw = json.loads(clean_json_text) # The final cleanup helper to ensure correct formatting cleaned_summary = _cleanup_llm_response(summary_data_raw) # SUCCESS: Update the database with the result and 'completed' status. print(f" - āœ… JOB ({checkin_id}): COMPLETED. Updating database with: {cleaned_summary}") supabase.table("influencer_weekly_checkins").update({ "structured_summary": cleaned_summary, "status": "completed" }).eq("id", checkin_id).execute() except Exception as e: error_message = f"AI model failed: {str(e)}" print(f" - āŒ JOB FAILED for check-in ID: {checkin_id}. Error: {error_message}") import traceback traceback.print_exc() supabase.table("influencer_weekly_checkins").update({ "status": "failed", "error_message": error_message }).eq("id", checkin_id).execute() @app.post("/generate-chat-response", response_model=ChatResponsePayload, summary="Interactive AI Strategist Chat") async def generate_chat_response_route(request: ChatResponseRequest): print(f"\nāœ… Received request on /generate-chat-response") if not _ai_strategist: raise HTTPException(status_code=503, detail="The AI Strategist is not available.") try: response_text = _ai_strategist.generate_chat_response(prompt=request.prompt, context=request.context) return ChatResponsePayload(response=response_text) except Exception as e: raise HTTPException(status_code=500, detail=str(e)) @app.post("/api/v1/chat", response_model=ChatAnswer, summary="Role-Aware AI Support Agent") async def ask_support_agent(query: ChatQuery): if not _support_agent: raise HTTPException(status_code=503, detail="AI Support Agent is not available.") return _support_agent.answer(payload=query.model_dump(), conversation_id=query.conversationId) @app.post("/api/v1/generate/caption", response_model=CaptionResponse, summary="Generate variations of a caption") async def generate_caption_route(request: CaptionRequest): if not _support_agent: raise HTTPException(status_code=503, detail="AI Support Agent is not available.") new_caption_text = _support_agent.generate_caption_variant(caption=request.caption, action=request.action) return CaptionResponse(new_caption=new_caption_text) @app.post("/generate-strategy", response_model=StrategyResponse, summary="Generate a Digital Marketing Strategy") async def generate_strategy_route(request: StrategyRequest): if not _support_agent: raise HTTPException(status_code=503, detail="AI Support Agent is not available.") try: strategy_text = _support_agent.generate_marketing_strategy(prompt=request.prompt) return StrategyResponse(response=strategy_text) except Exception as e: raise HTTPException(status_code=500, detail=f"An internal error occurred in the AI model: {e}") @app.post("/api/v1/predict/budget", response_model=BudgetResponse, summary="Predict Campaign Budget") async def predict_budget(request: BudgetRequest): if not _budget_predictor: raise HTTPException(status_code=503, detail="Budget predictor is not available.") input_data = pd.DataFrame([request.model_dump()]) prediction = _budget_predictor.predict(input_data)[0] return BudgetResponse(predicted_budget_usd=round(prediction, 2)) @app.post("/api/v1/match/influencers", response_model=MatcherResponse, summary="Match Influencers to Campaign") async def match_influencers(request: MatcherRequest): if not _influencer_matcher: raise HTTPException(status_code=503, detail="Influencer matcher is not available.") input_data = pd.DataFrame([request.model_dump()]) prediction = _influencer_matcher.predict(input_data) integer_ids = [int(pid) for pid in prediction] return MatcherResponse(suggested_influencer_ids=integer_ids) @app.post("/api/v1/predict/performance", response_model=PerformanceResponse, summary="Predict Campaign Performance") async def predict_performance(request: PerformanceRequest): if not _performance_predictor: raise HTTPException(status_code=503, detail="Performance predictor is not available.") input_data = pd.DataFrame([request.model_dump()]) prediction_value = _performance_predictor.predict(input_data)[0] return PerformanceResponse(predicted_engagement_rate=0.035, predicted_reach=int(prediction_value)) @app.post("/generate-outline", response_model=OutlineResponse, summary="Generate a Blog Post Outline") async def generate_outline_route(request: OutlineRequest): if not _support_agent: raise HTTPException(status_code=503, detail="AI Support Agent is not available.") try: outline_text = _support_agent.generate_content_outline(title=request.title) return OutlineResponse(outline=outline_text) except Exception as e: raise HTTPException(status_code=500, detail=f"An internal error occurred in the AI model: {e}") @app.post("/generate-dashboard-insights", response_model=StrategyResponse, summary="Generate Insights from Dashboard KPIs") @cached_response # <--- ✨ NEW: Speed Booster Logic ✨ async def generate_dashboard_insights_route(request: DashboardInsightsRequest): print(f"\nāœ… Received request on /generate-dashboard-insights with data: {request.model_dump()}") if not _llm_instance: raise HTTPException(status_code=503, detail="The Llama model is not available.") # Existing logic remains 100% SAME kpis = request.model_dump() prompt = f""" [SYSTEM] You are a senior data analyst at Reachify. You are writing a short, insightful summary for the agency's admin. Identify the most important trends from the week's KPIs. Write 2-3 human-readable bullet points. Be proactive and suggest an action. [THIS WEEK'S KPI DATA] - Revenue This Month (so far): ${kpis.get('total_revenue_monthly', 0):.2f} - New Users This Week: {kpis.get('new_users_weekly', 0)} - Currently Active Campaigns: {kpis.get('active_campaigns', 0)} - Items Awaiting Approval: {kpis.get('pending_approvals', 0)} [YOUR INSIGHTFUL BULLET POINTS] - """ try: print("--- Direct Call: Sending composed prompt to LLM...") response = _llm_instance(prompt, max_tokens=250, temperature=0.7, stop=["[SYSTEM]", "Human:", "\n\n"], echo=False) insight_text = response['choices'][0]['text'].strip() if not insight_text.startswith('-'): insight_text = '- ' + insight_text print("--- Direct Call: Successfully received response from LLM.") return StrategyResponse(response=insight_text) except Exception as e: print(f"🚨 AN ERROR OCCURRED DIRECTLY IN THE ENDPOINT:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.get("/", summary="Health Check") def read_root(): return {"status": "Unified AI Service is running"} @app.post("/predict/time-series", response_model=TimeSeriesForecastResponse, summary="Forecast Time Series with Trend Analysis") def predict_time_series(request: TimeSeriesForecastRequest): print(f"\nāœ… Received smart forecast request with context: '{request.business_context}'") if len(request.data) < 5: raise HTTPException(status_code=400, detail="Not enough data. At least 5 data points required.") try: df = pd.DataFrame([item.model_dump() for item in request.data]) df['date'] = pd.to_datetime(df['date']) df = df.set_index('date').asfreq('MS', method='ffill') model = Holt(df['value'], initialization_method="estimated").fit(optimized=True) forecast_result = model.forecast(steps=request.periods_to_predict) smart_forecast_output = [] last_historical_value = df['value'].iloc[-1] for date, predicted_val in forecast_result.items(): trend_label = "Stable" commentary = None percentage_change = ((predicted_val - last_historical_value) / last_historical_value) * 100 if percentage_change > 10: trend_label = "Strong Growth" if "by " in request.business_context: reason = request.business_context.split('by ')[-1] commentary = f"Strong growth expected, likely driven by {reason}" else: commentary = "Strong growth expected due to positive trends." elif percentage_change > 2: trend_label = "Modest Growth" elif percentage_change < -5: trend_label = "Potential Downturn" commentary = "Warning: A potential downturn is detected. This may not account for upcoming campaigns. Review your strategy." smart_forecast_output.append( SmartForecastDataPoint( date=date.strftime('%Y-%m-%d'), predicted_value=round(predicted_val, 2), trend=trend_label, commentary=commentary ) ) last_historical_value = predicted_val return TimeSeriesForecastResponse(forecast=smart_forecast_output) except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/generate-health-summary", response_model=HealthSummaryResponse, summary="Generates an actionable summary from KPIs") def generate_health_summary(request: HealthKpiRequest): print(f"\nāœ… Received request to generate health summary.") if not _llm_instance: raise HTTPException(status_code=503, detail="LLM not available for summary.") kpis = request.model_dump() prompt = f""" [SYSTEM] You are a business analyst. Analyze these KPIs: Platform Revenue (₹{kpis.get('platformRevenue', 0):,.0f}), Active Campaigns ({kpis.get('activeCampaigns', 0)}). Provide one [PROGRESS] point and one [AREA TO WATCH] with a next action. Under 50 words. [YOUR ANALYSIS] """ try: response = _llm_instance(prompt, max_tokens=150, temperature=0.6, stop=["[SYSTEM]"], echo=False) summary_text = response['choices'][0]['text'].strip() print(f" - āœ… Generated summary: {summary_text}") return HealthSummaryResponse(summary=summary_text) except OSError as e: print(f"🚨 CRITICAL LLM CRASH CAUGHT (OSError): {e}. Returning a fallback message.") traceback.print_exc() return HealthSummaryResponse(summary="[AREA TO WATCH]: The AI analyst model is currently unstable and is being reviewed. Manual analysis is recommended.") except Exception as e: print(f"🚨 An unexpected error occurred during summary generation: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/generate_team_strategy", response_model=TeamStrategyResponse, summary="Generates a full campaign strategy for the internal team") def generate_team_strategy(request: TeamStrategyRequest): """ This endpoint orchestrates the AI/ML logic for the Team Strategist tool. It takes campaign details and a list of influencers from the backend. """ print(f"\nāœ… Received request on /generate_team_strategy for brand: {request.brand_name}") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist model is not available or failed to load.") try: # Step 1: Generate the creative brief using the LLM creative_brief_dict = _ai_strategist.generate_campaign_brief( brand_name=request.brand_name, campaign_goal=request.campaign_goal, target_audience=request.target_audience, budget_range=request.budget_range ) if "error" in creative_brief_dict: raise Exception(f"LLM Error during brief generation: {creative_brief_dict['error']}") # Step 2: Rank the provided influencers using the ML model influencer_list_of_dicts = [inf.model_dump() for inf in request.influencers] suggested_influencers_list = rank_influencers_by_match( influencers=influencer_list_of_dicts, campaign_details=request.model_dump(exclude={"influencers"}), top_n=3 ) print("āœ… Successfully generated brief and ranked influencers.") return TeamStrategyResponse( success=True, strategy=CreativeBrief(**creative_brief_dict), suggested_influencers=[InfluencerData(**inf) for inf in suggested_influencers_list] ) except Exception as e: print(f"🚨 An error occurred in /generate_team_strategy endpoint:") traceback.print_exc() return TeamStrategyResponse(success=False, error=str(e)) @app.post("/strategist/generate-analytics-insights", response_model=AnalyticsInsightsResponse, summary="Generates Actionable Insights from Campaign Analytics") async def generate_analytics_insights_route(request: AnalyticsInsightsRequest): """ Receives campaign analytics data and uses the AI Strategist to generate key insights. """ print(f"\nāœ… Received request on /strategist/generate-analytics-insights") if not _ai_strategist: raise HTTPException(status_code=503, detail="The AI Strategist is not available.") try: # Pydantic model se data ko dictionary mein convert karein analytics_data = request.model_dump() # Naye function ko call karein insights_text = _ai_strategist.generate_analytics_insights(analytics_data=analytics_data) return AnalyticsInsightsResponse(insights=insights_text) except Exception as e: print(f"🚨 An error occurred in /strategist/generate-analytics-insights endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/predictor/rank-influencers", response_model=InfluencerRankResponse, summary="Ranks a given list of influencers for a specific campaign") async def rank_influencers_route(request: InfluencerRankRequest): """ Backend se campaign details aur sabhi influencers ki list leta hai, aur ML model ka istemal karke top 3 ranked influencers wapas bhejta hai. """ print(f"\nāœ… Received request on /predictor/rank-influencers for campaign: '{request.campaign_details.description[:30]}...'") try: influencers_list = [inf.model_dump() for inf in request.influencers] campaign_details_dict = request.campaign_details.model_dump() ranked_list = rank_influencers_by_match( influencers=influencers_list, campaign_details=campaign_details_dict, top_n=5 ) print(f" - āœ… Successfully ranked {len(ranked_list)} influencers.") return InfluencerRankResponse(ranked_influencers=ranked_list) except Exception as e: print(f"🚨 An error occurred in /predictor/rank-influencers endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/strategist/generate-weekly-summary", response_model=WeeklySummaryResponse, summary="Generates a Weekly Summary from Metrics") def generate_weekly_summary_route(request: WeeklySummaryRequest): print(f"\nāœ… Received request on the NEW /strategist/generate-weekly-summary endpoint.") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not initialized.") try: summary_text = _ai_strategist.generate_weekly_summary(metrics=request.model_dump()) if not summary_text or "error" in summary_text.lower(): raise Exception("AI model failed to generate a valid summary.") return WeeklySummaryResponse(summary=summary_text) except Exception as e: print(f"🚨 An error occurred in /strategist/generate-weekly-summary: {e}") raise HTTPException(status_code=500, detail=str(e)) @app.post("/predict/payout_forecast", response_model=PayoutForecastOutput, summary="Predicts future influencer payouts for a manager") def predict_payout(data: PayoutForecastInput): """ Predicts the estimated influencer payout for the next 30 days based on the total budget of a manager's active campaigns. """ print(f"\nāœ… Received request on /predict/payout_forecast") if not _payout_forecaster: raise HTTPException(status_code=503, detail="Model is not available. Please train the payout forecaster model first.") try: # Prediction ke liye data ko sahi DataFrame format mein convert karo input_df = pd.DataFrame([{'budget': data.total_budget_active_campaigns}]) # Prediction karo prediction = _payout_forecaster.predict(input_df)[0] # Ensure the prediction is never negative forecasted_amount = max(0, float(prediction)) print(f" - āœ… Generated payout forecast: {forecasted_amount}") return { "forecastedAmount": forecasted_amount, "commentary": "Based on the total budget of your current active campaigns." } except Exception as e: print(f"🚨 An error occurred in /predict/payout_forecast endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=f"An error occurred during prediction: {str(e)}") @app.post("/analyze/content_quality", response_model=ContentQualityResponse, summary="Analyzes a caption for a quality score") def analyze_content_quality(request: ContentQualityRequest): """ Uses the loaded LLM to analyze a social media caption based on several criteria and returns a quantitative score and qualitative feedback. """ print(f"\nāœ… Received request on /analyze/content_quality") if not _llm_instance: raise HTTPException(status_code=503, detail="The Llama model is not available.") caption = request.caption # This is a very structured prompt that asks the LLM to act as a specialist # and return a JSON object, which is easier and more reliable to parse. prompt = f""" [SYSTEM] You are a social media expert. Analyze the following caption based on four criteria: Readability, Engagement, Call to Action (CTA), and Hashtag Strategy. For each criterion, provide a score from 1 (poor) to 10 (excellent). Also, provide a final overall score (average of the four scores) and short, actionable feedback. Respond ONLY with a valid JSON object in the following format: {{ "overall_score": , "scores": {{ "readability": , "engagement": , "call_to_action": , "hashtag_strategy": }}, "feedback": "" }} [CAPTION TO ANALYZE] "{caption}" [YOUR JSON RESPONSE] """ try: print("--- Sending caption to LLM for quality analysis...") response = _llm_instance(prompt, max_tokens=512, temperature=0.2, stop=["[SYSTEM]", "\n\n"], echo=False) # Extract the JSON part of the response json_text = response['choices'][0]['text'].strip() # Find the start and end of the JSON object start_index = json_text.find('{') end_index = json_text.rfind('}') + 1 if start_index == -1 or end_index == 0: raise ValueError("LLM did not return a valid JSON object.") clean_json_text = json_text[start_index:end_index] import json analysis_result = json.loads(clean_json_text) print("--- Successfully received and parsed JSON response from LLM.") return ContentQualityResponse(**analysis_result) except (json.JSONDecodeError, KeyError, ValueError) as e: print(f"🚨 ERROR parsing LLM response: {e}. Raw response was: {json_text}") raise HTTPException(status_code=500, detail="Failed to parse the analysis from the AI model. The model may have returned an unexpected format.") except Exception as e: print(f"🚨 An unexpected error occurred during content analysis: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/rank/campaigns-for-influencer", response_model=RankCampaignsResponse, summary="Ranks a list of campaigns for one influencer") async def rank_campaigns_for_influencer_route(request: RankCampaignsRequest): """ Takes an influencer's profile and a list of campaigns, uses the ML model to predict a 'match score' for each, and returns the list ranked by that score. """ print(f"\nāœ… Received request on /rank/campaigns-for-influencer for influencer: {request.influencer.id}") # 1. Security Check: Model loaded hai ya nahi? if not _influencer_matcher: raise HTTPException(status_code=503, detail="Influencer Matcher model is not available.") if not request.campaigns: return RankCampaignsResponse(ranked_campaigns=[]) try: # 2. Data Preparation: Model ke liye DataFrame banayein # Model ko wahi columns chahiye jin par woh train hua tha. df_list = [] for campaign in request.campaigns: df_list.append({ 'influencer_category': request.influencer.category, 'influencer_bio': request.influencer.bio, 'campaign_description': campaign.description, # Hum woh columns bhi denge jo is context me nahi hain, par model ko chahiye 'followers': 50000, # Ek average value 'engagement_rate': 0.04, # Ek acchi value 'country': 'USA', # Ek default value 'niche': request.influencer.category or 'lifestyle' }) df_to_predict = pd.DataFrame(df_list) # 3. šŸ”„ AI Prediction (The Missing Part) šŸ”„ # Model se har campaign ke liye ek score predict karwayein print(f" - Predicting scores for {len(df_to_predict)} campaigns...") predicted_scores = _influencer_matcher.predict(df_to_predict) # 4. Sorting & Ranking # Campaigns ko unke score ke saath combine karein results_with_scores = zip(request.campaigns, predicted_scores) # Unhein score ke hisaab se sort karein (zyada score upar) sorted_results = sorted(results_with_scores, key=lambda x: x[1], reverse=True) # 5. Final Jawab (Response) taiyaar karein output = [ RankedCampaignResult(campaign_id=camp.id, score=float(score)) for camp, score in sorted_results ] print(f" - āœ… Successfully scored and ranked campaigns.") return RankCampaignsResponse(ranked_campaigns=output) except Exception as e: print(f"🚨 An error occurred during campaign ranking:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/ai/assist/caption", response_model=CaptionAssistResponse, summary="Assists with writing or improving captions") async def caption_assistant_route(request: CaptionAssistRequest): """ Takes a caption and performs an action (improve, suggest hashtags, etc.) using the LLM. """ print(f"\nāœ… Received request on /ai/assist/caption with action: {request.action}") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # _ai_strategist ke andar ek naya function banayenge generated_text = _ai_strategist.get_caption_assistance( caption=request.caption, action=request.action, guidelines=request.guidelines ) return CaptionAssistResponse(new_text=generated_text) except Exception as e: print(f"🚨 An error occurred in /ai/assist/caption endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/predict/campaign-outcome", response_model=ForecastResponse, summary="Forecasts influencer performance and earnings for a campaign") async def predict_campaign_outcome(request: ForecastRequest): """ Takes campaign and influencer stats and uses ML models to predict performance (reach, engagement) and potential earnings. """ print(f"\nāœ… Received request on /predict/campaign-outcome") if not _performance_predictor or not _payout_forecaster: raise HTTPException(status_code=503, detail="Forecasting models are not available.") try: # āœ… THE FIX IS HERE: Create a single 'budget' column. # Column names MUST match the training script's columns. input_data = pd.DataFrame([{ 'budget': request.budget, 'category': request.category, 'influencer_count': 1, 'platform': 'instagram', 'location': 'USA', 'followers': request.follower_count, 'engagement_rate': request.engagement_rate }]) # --- Performance Prediction --- print(" - Predicting performance...") # āœ… THE FIX: Pass the columns the model ACTUALLY needs. performance_model_cols = ['budget', 'influencer_count', 'platform', 'location', 'category'] reach_prediction = _performance_predictor.predict(input_data[performance_model_cols])[0] engagement_prediction = request.engagement_rate * 100 perf_forecast = PerformanceForecast( predicted_reach=int(reach_prediction), predicted_engagement_rate=round(engagement_prediction, 2) ) # --- Payout Prediction --- print(" - Predicting payout...") # This model only needs 'budget' payout_prediction = _payout_forecaster.predict(input_data[['budget']])[0] payout_forecast = PayoutForecast( estimated_earning=max(0, float(payout_prediction)) ) print(" - āœ… Successfully generated forecasts.") return ForecastResponse(performance=perf_forecast, payout=payout_forecast) except Exception as e: print(f"🚨 An error occurred during outcome prediction:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/ai/summarize/influencer-analytics", response_model=InfluencerAnalyticsSummaryResponse, summary="Generates a summary for the influencer's analytics page") async def summarize_influencer_analytics(request: InfluencerKpiData): """ Takes an influencer's KPIs and uses the AI strategist to create an actionable summary. """ print(f"\nāœ… Received request on /ai/summarize/influencer-analytics") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # Pass the data as a dictionary to the strategist summary_text = _ai_strategist.generate_influencer_analytics_summary(kpis=request.model_dump()) return InfluencerAnalyticsSummaryResponse(summary=summary_text) except Exception as e: print(f"🚨 An error occurred in the analytics summary endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/portfolio/curate-with-ai", response_model=CuratePortfolioResponse) def curate_portfolio_with_ai(request: CuratePortfolioRequest): """ Accepts a list of approved submissions, scores them based on simple logic, and returns the IDs of the best ones. THIS VERSION DOES NOT USE THE LLM. """ print(f"\nāœ…āœ…āœ… RUNNING FINAL, NON-LLM VERSION of Portfolio Curation āœ…āœ…āœ…") submissions = request.submissions if not submissions: return CuratePortfolioResponse(featured_submission_ids=[]) scored_submissions = [] for sub in submissions: # Step 1: Ek score calculate karein score = 0 # Likes ke liye points (sabse zaroori) score += (sub.likes or 0) * 0.7 # Caption lamba hai to extra points if sub.caption and len(sub.caption) > 100: score += 100 # Ek boost # Step 2: Har submission ko uske score ke saath save karein scored_submissions.append({'id': sub.id, 'score': score}) # Step 3: Sabhi submissions ko score ke hisaab se sort karein sorted_submissions = sorted(scored_submissions, key=lambda x: x['score'], reverse=True) # Step 4: Sabse behtareen 5 submissions ko chunein (ya jitne bhi hain) top_submissions = sorted_submissions[:5] # Step 5: Sirf unki ID waapis bhejein featured_ids = [sub['id'] for sub in top_submissions] print(f" - āœ… Scored and selected {len(featured_ids)} posts: {featured_ids}") return CuratePortfolioResponse(featured_submission_ids=featured_ids) @app.post("/tasks/prioritize", response_model=TaskPrioritizationResponse) def prioritize_task(request: TaskPrioritizationRequest): """ Analyzes a task's title and description to assign a priority level. """ if not _llm_instance: raise HTTPException(status_code=503, detail="LLM model is not available.") prompt = f""" [INST] You are an expert assistant for a social media influencer. Your job is to assign a priority to a new task based on its title. Use these rules: - If the task mentions "revise", "rejection", "feedback", "contract", or is a deadline, the priority is "high". - If the task is about a "new invitation", "new opportunity", or "message", the priority is "medium". - For anything else like "update profile", "explore campaigns", the priority is "low". Respond ONLY with one of the following words: high, medium, or low. Task Title: "{request.title}" [/INST] """ try: print(f" - šŸ¤– Prioritizing task: '{request.title}'") output = _llm_instance(prompt, max_tokens=10, stop=["[INST]"], echo=False) # LLM se aaye response ko saaf karein priority = output['choices'][0]['text'].strip().lower() # Ek safety check, taaki LLM kuch galat na bhej de if priority not in ['high', 'medium', 'low']: print(f" - āš ļø LLM returned invalid priority: '{priority}'. Defaulting to 'medium'.") priority = 'medium' print(f" - āœ… AI assigned priority: '{priority}'") return TaskPrioritizationResponse(priority=priority) except Exception as e: print(f" - āŒ An unexpected error occurred during task prioritization: {e}") return TaskPrioritizationResponse(priority='medium') @app.post("/predict/earning-opportunities", response_model=EarningOpportunityResponse, summary="Finds the best earning opportunities for an influencer") async def predict_earning_opportunities(request: EarningOpportunityRequest): """ Based on an influencer's follower count, the AI model estimates their potential performance score across various campaign types. (SIMPLIFIED) """ print(f"\nāœ… Received request on /predict/earning-opportunities (SIMPLIFIED)") if _earnings_optimizer is None or _earnings_encoder is None: raise HTTPException(status_code=503, detail="Earning Optimizer model or encoder is not available.") try: # === ✨ THE FIX STARTS HERE ✨ === # Step 1: Create scenarios in a DataFrame scenarios_list = [ {'campaign_niche': niche, 'content_format': c_format, 'follower_count': request.follower_count} for niche in ['Tech', 'Fashion', 'Food', 'Gaming', 'General'] for c_format in ['Reel', 'Post', 'Story'] ] df_scenarios = pd.DataFrame(scenarios_list) # Step 2: Manually encode the categorical features using the saved encoder print(" - Manually encoding data using saved encoder...") categorical_features = ['campaign_niche', 'content_format'] encoded_cats = _earnings_encoder.transform(df_scenarios[categorical_features]) encoded_df = pd.DataFrame(encoded_cats, columns=_earnings_encoder.get_feature_names_out(categorical_features)) # Step 3: Combine with numerical features numerical_features = df_scenarios[['follower_count']].reset_index(drop=True) X_final_to_predict = pd.concat([encoded_df, numerical_features], axis=1) # Step 4: Predict using the simple model print(f" - Predicting scores for {len(X_final_to_predict)} scenarios...") predicted_scores = _earnings_optimizer.predict(X_final_to_predict) # === ✨ THE FIX ENDS HERE ✨ === # ... (The result formatting part is exactly the same as before) results = [] for i, scenario in enumerate(scenarios_list): score = float(predicted_scores[i]) comment = "This could be a good opportunity." if score > 0.75: comment = "Excellent Opportunity! Focus on this." elif score < 0.4: comment = "May not be the best fit for you." results.append(Opportunity( campaign_niche=scenario['campaign_niche'], content_format=scenario['content_format'], estimated_score=score, commentary=comment )) sorted_results = sorted(results, key=lambda x: x.estimated_score, reverse=True) return EarningOpportunityResponse(opportunities=sorted_results[:5]) except Exception as e: print("🚨 An error occurred in /predict/earning-opportunities endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/predict/post-performance", response_model=PostPerformanceResponse, summary="Predicts likes and comments for a new post") async def predict_post_performance(request: PostPerformanceRequest): """ Takes details of a potential post and uses two ML models to predict the number of likes and comments it might receive. """ print(f"\nāœ… Received request on /predict/post-performance") if not _likes_predictor or not _comments_predictor: raise HTTPException(status_code=503, detail="Performance prediction models are not available.") try: # Step 1: Prepare the input data in a DataFrame, just like during training input_data = pd.DataFrame([request.model_dump()]) # Step 2: Use the models to predict print(" - Predicting likes...") predicted_likes_raw = _likes_predictor.predict(input_data)[0] print(" - Predicting comments...") predicted_comments_raw = _comments_predictor.predict(input_data)[0] # Step 3: Clean the predictions (e.g., ensure they are not negative) predicted_likes = max(0, int(predicted_likes_raw)) predicted_comments = max(0, int(predicted_comments_raw)) # Step 4: Generate simple, rule-based feedback feedback_messages = [] if request.caption_length < 50: feedback_messages.append("Consider writing a slightly longer caption to increase engagement.") elif request.caption_length > 800: feedback_messages.append("This is a long caption! Ensure the first line is very engaging.") else: feedback_messages.append("The caption length is good for engagement.") if request.campaign_niche == 'General': feedback_messages.append("Try to target a more specific niche in the future for better performance.") feedback_text = " ".join(feedback_messages) print(" - āœ… Successfully generated performance prediction and feedback.") return PostPerformanceResponse( predicted_likes=predicted_likes, predicted_comments=predicted_comments, feedback=feedback_text ) except Exception as e: print(f"🚨 An error occurred in the post-performance endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.get("/analyze/performance-anomalies", response_model=List[AnomalyInsight], summary="Finds unusual performance trends for all influencers") def analyze_anomalies(supabase: Client = Depends(get_supabase_client)): # This endpoint is heavy, so it should have security (e.g., requires an admin API key) print("šŸ¤– Running platform-wide Anomaly Detection...") try: # 1. Fetch historical data for all influencers from our new stats table stats_res = supabase.table('daily_influencer_stats').select('*').order('date', desc=True).limit(5000).execute() # Get last ~5000 entries profiles_res = supabase.table('profiles').select('id, full_name').eq('role', 'influencer').execute() if not stats_res.data: return [] all_stats_df = pd.DataFrame(stats_res.data) profiles_map = {p['id']: p['full_name'] for p in profiles_res.data} all_insights = [] # 2. Loop through each influencer for influencer_id, group in all_stats_df.groupby('profile_id'): historical_df = group.sort_values('date') today_stats = historical_df.iloc[-1].to_dict() # 3. Call the Anomaly Detector AI insights = find_anomalies(influencer_id, historical_df, today_stats) if insights: all_insights.append(AnomalyInsight( influencer_id=influencer_id, influencer_name=profiles_map.get(influencer_id, 'Unknown Influencer'), insights=insights )) return all_insights except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/predict/revenue-forecast", response_model=RevenueForecastResponse, summary="Generates a 3-month revenue forecast") async def predict_revenue_forecast(): """ (FAST VERSION) Uses the trained Holt's model to forecast revenue and adds simple commentary. """ print(f"\nāœ… Received request on /predict/revenue-forecast (FAST VERSION)") if not _revenue_forecaster: raise HTTPException(status_code=503, detail="Revenue forecasting model is not available.") try: # Step 1: Generate forecast (This is fast) forecast_result = _revenue_forecaster.forecast(steps=3) # Step 2: Format the output and add trend analysis (Also fast) forecast_datapoints = [] last_historical_value = _revenue_forecaster.model.endog[-1] for timestamp, predicted_value in forecast_result.items(): trend_label = "Stable" percentage_change = ((predicted_value - last_historical_value) / last_historical_value) * 100 if percentage_change > 15: trend_label = "Strong Growth" elif percentage_change > 5: trend_label = "Modest Growth" elif percentage_change < -10: trend_label = "Potential Downturn" forecast_datapoints.append(RevenueForecastDatapoint( month=timestamp.strftime('%B %Y'), predicted_revenue=round(predicted_value, 2), trend=trend_label )) last_historical_value = predicted_value # Step 3: Use simple, rule-based commentary (This is instant) first_trend = forecast_datapoints[0].trend if forecast_datapoints else "Stable" ai_commentary = "AI Insight: The forecast shows a stable outlook for the coming quarter." if "Growth" in first_trend: ai_commentary = "AI Insight: The model predicts a positive growth trend for the next quarter." elif "Downturn" in first_trend: ai_commentary = "AI Insight: A potential slowdown is predicted. It's a good time to review upcoming campaigns." print(" - āœ… Successfully generated revenue forecast (fast method).") return RevenueForecastResponse( forecast=forecast_datapoints, ai_commentary=ai_commentary ) except Exception as e: print(f"🚨 An error occurred in the revenue forecast endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/predict/influencer-performance", response_model=InfluencerPerformanceResponse, summary="Predicts a holistic performance score for an influencer") async def predict_influencer_performance(stats: InfluencerPerformanceStats): """ Takes an influencer's key performance metrics and returns a single, AI-generated performance score from 0-100. """ print(f"\nāœ… Received request on /predict/influencer-performance") if not _performance_scorer: raise HTTPException(status_code=503, detail="The Performance Scorer model is not available. Please train it first.") try: # Input data ko DataFrame mein convert karein, jaisa model ko chahiye input_data = pd.DataFrame([stats.model_dump()]) # Model se prediction karein score = _performance_scorer.predict(input_data) # Score ko saaf karke 0-100 ke beech rakhein predicted_score = max(0, min(100, int(score[0]))) print(f" - āœ… Successfully predicted performance score: {predicted_score}") return {"performance_score": predicted_score} except Exception as e: print(f"🚨 An error occurred in the influencer performance endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/v1/match/rank-by-similarity", response_model=RankBySimilarityResponse, summary="Generic endpoint to rank documents by text similarity") async def rank_by_similarity_endpoint(request: RankBySimilarityRequest): print(f"\nāœ… Received request on /v1/match/rank-by-similarity") try: documents_list = [doc.model_dump(exclude_unset=True) for doc in request.documents] ranked_docs = rank_documents_by_similarity(query=request.query, documents=documents_list) print(f" - āœ… Successfully ranked {len(ranked_docs)} documents.") return RankBySimilarityResponse(ranked_documents=ranked_docs) except Exception as e: print(f"🚨 An error occurred in the ranking endpoint:") import traceback traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/analyze/content-quality", response_model=ContentQualityResponse, summary="Analyzes a caption for a quality score") def analyze_content_quality(request: ContentQualityRequest): """ Uses the loaded LLM to analyze a social media caption and returns a robustly parsed response. """ print(f"\nāœ… Received request on /analyze/content-quality") if not _llm_instance: raise HTTPException(status_code=503, detail="The Llama model is not available.") caption = request.caption prompt = f""" [SYSTEM] You are a social media expert. Analyze the following caption... Respond ONLY with a valid JSON object in the following format: {{ "overall_score": , "scores": {{ "readability": , "engagement": , "call_to_action": , "hashtag_strategy": }}, "feedback": "" }} [CAPTION TO ANALYZE] "{caption}" [YOUR JSON RESPONSE] """ try: print("--- Sending caption to LLM for quality analysis...") response = _llm_instance(prompt, max_tokens=512, temperature=0.2, stop=["[SYSTEM]", "\n\n"], echo=False) json_text = response['choices'][0]['text'].strip() start_index = json_text.find('{') end_index = json_text.rfind('}') + 1 if start_index == -1 or end_index == 0: raise ValueError("LLM did not return a valid JSON object.") clean_json_text = json_text[start_index:end_index] import json analysis_result_raw = json.loads(clean_json_text) final_result = { "overall_score": analysis_result_raw.get("overall_score"), "feedback": analysis_result_raw.get("feedback"), "scores": analysis_result_raw.get("scores") or analysis_result_raw.get("score") } print("--- Successfully received and parsed JSON response from LLM.") return ContentQualityResponse(**final_result) except (json.JSONDecodeError, KeyError, ValueError) as e: print(f"🚨 ERROR parsing LLM response: {e}. Raw response was: {json_text}") raise HTTPException(status_code=500, detail="Failed to parse analysis from AI model.") except Exception as e: print(f"🚨 An unexpected error occurred during content analysis:") import traceback traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/generate/daily-briefing", response_model=DailyBriefingResponse, summary="Generates a daily action plan for the Talent Manager") def generate_daily_briefing(data: DailyBriefingData): """ Takes various KPIs from the backend, synthesizes them, and uses the LLM to generate a short, actionable daily briefing for a Talent Manager. """ print(f"\nāœ… Received request on /generate/daily-briefing") if not _llm_instance: raise HTTPException(status_code=503, detail="The Llama model is not available for briefing.") # --- ✨ THE FINAL "IDIOT-PROOF" PROMPT FOR TINYLLAMA --- final_prompt = f""" Summarize these key points into 2-3 direct bullet points for a manager. DATA: - Influencers without campaigns: {data.on_bench_influencers} - Submissions needing review: {data.pending_submissions + data.revisions_requested} - Total pending money: {data.highest_pending_payout:,.0f} INR SUMMARY: - """ try: print("--- Sending briefing data to LLM (Idiot-Proof prompt)...") # Temperature 0.1 karne se model aur zyada factual aur kam creative hoga response = _llm_instance(final_prompt, max_tokens=150, temperature=0.1, stop=["DATA:"], echo=False) briefing_text = response['choices'][0]['text'].strip() # Add our own header to make it look nice final_briefing = f"Here are your top priorities for today:\n- {briefing_text}" print("--- Successfully generated daily briefing.") return DailyBriefingResponse(briefing_text=final_briefing) except Exception as e: print(f"🚨 An unexpected error occurred during briefing generation:") import traceback traceback.print_exc() raise HTTPException(status_code=500, detail="Failed to generate AI briefing.") @app.post("/summarize-contract", response_model=ContractSummary, summary="Analyzes a PDF contract and extracts key terms") def summarize_contract(request: ContractURL): print(f"\nāœ… Received request on /summarize-contract (v3 - ROBUST)") if not _llm_instance: raise HTTPException(status_code=503, detail="The Llama model is not available.") try: print(" - šŸ“‘ Parsing PDF from URL...") contract_text = parse_pdf_from_url(request.pdf_url) contract_text = contract_text[:4000] # Truncate print(f" - āœ… PDF parsed successfully. Truncated to {len(contract_text)} chars.") final_prompt = f""" [INST] You are a legal analysis AI. Your task is to extract specific details from a contract. You MUST respond ONLY with a single, valid JSON object. Do not add any text before or after the JSON. **RULES FOR THE JSON VALUES:** 1. All values for "payment_details", "deliverables", "deadlines", "exclusivity", and "ownership" MUST be a single, plain string. 2. The value for "summary_points" MUST be a simple list of strings. 3. DO NOT use nested objects. DO NOT use nested lists. Summarize the content into plain text. [EXAMPLE of a GOOD RESPONSE] {{ "payment_details": "Client agrees to pay Influencer a total fee of $5,000 USD, payable in two installments.", "deliverables": "Influencer must create 2 Instagram Reels and 5 Instagram Stories.", "deadlines": "The deadline for all deliverables is October 30, 2024.", "exclusivity": "Influencer agrees to an exclusivity period of 30 days post-campaign.", "ownership": "The Client retains ownership of all created content.", "summary_points": [ "Total payment is $5,000 USD.", "Deliverables: 2 Reels, 5 Stories.", "A 30-day exclusivity period applies after the campaign." ] }} [/EXAMPLE] Now, based on these strict rules, analyze the following text: [CONTRACT TEXT] {contract_text} [/CONTRACT TEXT] [YOUR JSON RESPONSE] """ print(" - šŸ“ž Calling LLM with the new, stricter prompt...") response = _llm_instance( final_prompt, max_tokens=1024, temperature=0.0, # Set to 0 for maximum factuality echo=False ) raw_response_text = response['choices'][0]['text'].strip() print(" - āš™ļø Parsing JSON response from LLM...") try: start_index = raw_response_text.find('{') end_index = raw_response_text.rfind('}') + 1 clean_json_text = raw_response_text[start_index:end_index] summary_data = json.loads(clean_json_text) except Exception as e: print(f"🚨 ERROR parsing LLM response: {e}. Raw response was: '{raw_response_text}'") raise HTTPException(status_code=500, detail="Failed to parse analysis from the AI model.") print("--- āœ… Successfully generated contract summary from LLM.") # We now return the raw dictionary. FastAPI will validate it against our simple ContractSummary model. return summary_data except Exception as e: traceback.print_exc() raise HTTPException(status_code=500, detail="An internal server error occurred in the AI.") @app.post("/predict/influencer-performance-score", response_model=InfluencerPerformanceResponse, summary="Predicts a holistic performance score for an influencer") async def predict_influencer_performance_score(stats: InfluencerPerformanceStats): """ Backend se influencer ki stats leta hai aur pre-trained model ka use karke ek performance score (0-100) return karta hai. """ print(f"\nāœ… Received request on /predict/influencer-performance-score") # Safety Check: Kya model load hua tha startup par? if _performance_scorer is None: print(" - āŒ ERROR: The Performance Scorer model (_performance_scorer) is not loaded.") raise HTTPException( status_code=503, detail="The Performance Scorer model is not available. Please ensure 'performance_scorer_v1.joblib' exists and is loaded." ) try: # Step 1: Backend se aaye data ko Pandas DataFrame mein badlo. # Column ke naam training ke waqt use hue naamo se bilkul match hone chahiye. input_data = pd.DataFrame([stats.model_dump()]) print(f" - Input data for model: \n{input_data}") # Step 2: Loaded model se prediction karo. predicted_score_raw = _performance_scorer.predict(input_data) # Step 3: Jawab ko saaf-suthra karo. # Score ko integer banao aur 0 se 100 ke beech rakho. predicted_score = max(0, min(100, int(predicted_score_raw[0]))) print(f" - āœ… Successfully predicted performance score: {predicted_score}") # Step 4: Sahi format mein jawab wapas bhejo. return InfluencerPerformanceResponse(performance_score=predicted_score) except Exception as e: print(f"🚨 An error occurred in the /predict/influencer-performance-score endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/ai/coach/generate-growth-plan", response_model=AIGrowthPlanResponse, summary="Generates personalized growth tips for a single influencer") def generate_growth_plan_route(request: AIGrowthPlanRequest): """ Backend se ek influencer ka live performance data leta hai aur LLM ka use karke personalized improvement tips generate karta hai. """ print(f"\nāœ… Received request on /ai/coach/generate-growth-plan for: {request.fullName}") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # Pydantic model ko dictionary mein convert karke strategist ko bhejein insights_list = _ai_strategist.generate_influencer_growth_plan(request.model_dump()) return AIGrowthPlanResponse(insights=insights_list) except Exception as e: print(f"🚨 An error occurred in the Growth Plan endpoint: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/analyze/brand-asset-colors", response_model=BrandAssetAnalysisResponse, summary="Extracts dominant colors from a logo URL") def analyze_brand_asset_colors(request: BrandAssetAnalysisRequest): """ Takes an image URL (logo/product), downloads it in memory, and uses AI (KMeans Clustering) to extract the main brand colors. """ print(f"\nāœ… Received request on /analyze/brand-asset-colors") try: # Utility function call colors = extract_colors_from_url(request.file_url) print(f" - āœ… Extracted colors: {colors}") return BrandAssetAnalysisResponse(dominant_colors=colors) except Exception as e: print(f"🚨 An error occurred during color extraction:") traceback.print_exc() # Fail gracefully return BrandAssetAnalysisResponse(dominant_colors=["#000000"]) @app.post("/generate/service-blueprint", response_model=ServiceBlueprintResponse, summary="Generates an AI project plan for a service") async def generate_service_blueprint_route(request: ServiceBlueprintRequest): """ Takes a service type and user requirements, then uses the AI Strategist to generate a structured project plan (blueprint). """ print(f"\nāœ… Received request on /generate/service-blueprint for type: {request.service_type}") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # Call the new method in our strategist blueprint_data = _ai_strategist.generate_service_blueprint( service_type=request.service_type, requirements=request.requirements ) # Check if the AI returned an error internally if "error" in blueprint_data: raise HTTPException(status_code=500, detail=blueprint_data["error"]) return ServiceBlueprintResponse(**blueprint_data) except HTTPException as http_exc: # Re-raise known HTTP exceptions raise http_exc except Exception as e: print(f"🚨 An unexpected error occurred in the blueprint endpoint:") traceback.print_exc() raise HTTPException(status_code=500, detail="An internal server error occurred while generating the blueprint.") @app.post("/generate/growth-plan", response_model=ServiceBlueprintResponse, summary="Generates an AI management plan for an influencer") async def generate_growth_plan_route(request: GrowthPlanRequest): """ Takes influencer goals and uses the AI Strategist to generate a growth plan. """ print(f"\nāœ… Naya Endpoint Hit: /generate/growth-plan for handle: {request.platform_handle}") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # Naye, alag function ko call karo blueprint_data = _ai_strategist.generate_growth_plan( platform_handle=request.platform_handle, goals=request.goals, challenges=request.challenges ) if "error" in blueprint_data: raise HTTPException(status_code=500, detail=blueprint_data["error"]) return ServiceBlueprintResponse(**blueprint_data) except HTTPException as http_exc: raise http_exc except Exception as e: print(f"🚨 Unexpected error in growth plan endpoint: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail="An internal server error occurred.") @app.post("/submit_summary_job") def submit_summary_job(request: AISummaryJobRequest, background_tasks: BackgroundTasks): """ Accepts a job, responds INSTANTLY, and runs the AI in the background. """ print(f" - āœ… Job accepted for check-in ID: {request.checkin_id}. Starting in background...") background_tasks.add_task(process_summary_in_background, request.checkin_id, request.raw_text) return {"message": "Job accepted", "checkin_id": request.checkin_id} @app.post("/generate/weekly-plan", response_model=WeeklyPlanResponse, summary="Generates 3 content tasks for an influencer") def generate_weekly_plan_route(request: WeeklyPlanRequest): # <--- async hata diya """ Takes influencer context (mood, niche, trends) and generates 3 tailored content options. """ print(f"\nāœ… Received request on /generate/weekly-plan") if not _ai_strategist: raise HTTPException(status_code=503, detail="AI Strategist is not available.") try: # Convert Pydantic model to dict context_dict = request.context.model_dump() # Call Strategist (Ab ye thread pool mein chalega) plan_data = _ai_strategist.generate_weekly_content_plan(context_dict) return WeeklyPlanResponse(**plan_data) except Exception as e: print(f"🚨 Error in weekly plan endpoint: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail=str(e)) @app.post("/chat/creative", response_model=Dict[str, str], summary="Brainstorming chat with AI Creative Director") def creative_chat_endpoint(request: CreativeChatRequest): if not _creative_director: raise HTTPException(status_code=503, detail="The AI Creative Director is not available due to a startup error.") try: history_list = [m.model_dump() for m in request.history] response_text = _creative_director.chat( user_message=request.message, history=history_list, task_context=request.task_context ) return {"reply": response_text} except Exception as e: print(f"🚨 Creative Chat Error: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail="An error occurred with the AI Director.") @app.post("/generate/final-from-chat", response_model=FinalScriptResponse, summary="Generates final structured script from chat history") def finalize_script_endpoint(request: FinalizeScriptRequest): if not _creative_director: raise HTTPException(status_code=503, detail="The AI Creative Director is not available due to a startup error.") try: history_list = [m.model_dump() for m in request.history] return _creative_director.generate_final_plan( task_context=request.task_context, history=history_list ) except Exception as e: print(f"🚨 Finalize Script Error: {e}") traceback.print_exc() raise HTTPException(status_code=500, detail="Failed to generate the final plan.")