from fastapi import FastAPI from fastapi.responses import HTMLResponse from pydantic import BaseModel from typing import List from transformers import pipeline app = FastAPI(title="Sentimind API") # Load sentiment analysis model sentiment_analyzer = pipeline( "sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english" ) class InputText(BaseModel): text: str class InputBatch(BaseModel): texts: List[str] @app.get("/", response_class=HTMLResponse) def root(): """Landing page with branding + API info""" return """ Sentimind API

🧠 Sentimind API

Welcome to Sentimind Labs sentiment analysis service for financial insights.

Available Endpoints

Example Usage

Single analysis:

POST /v1/analyze/sentiment/single
{
  "text": "Apple stock is set to rally after strong iPhone sales."
}
                

Batch analysis:

POST /v1/analyze/sentiment/batch
{
  "texts": [
    "Tesla shares might drop due to weaker demand in China.",
    "Microsoft reported record cloud revenue growth."
  ]
}
                
""" @app.get("/v1/health") def health_check(): return {"status": "ok", "service": "Sentimind API", "version": "v1"} @app.post("/v1/analyze/sentiment/single") def analyze_single(input_data: InputText): result = sentiment_analyzer(input_data.text)[0] return { "input_text": input_data.text, "sentiment": result['label'].lower(), "confidence": float(result['score']) } @app.post("/v1/analyze/sentiment/batch") def analyze_batch(input_data: InputBatch): results = [] positive_count = 0 negative_count = 0 for text in input_data.texts: result = sentiment_analyzer(text)[0] sentiment = result['label'].lower() confidence = float(result['score']) results.append({ "text": text, "sentiment": sentiment, "confidence": confidence }) if sentiment == "positive": positive_count += 1 else: negative_count += 1 total = len(input_data.texts) positive_ratio = positive_count / total if total > 0 else 0 negative_ratio = negative_count / total if total > 0 else 0 overall_sentiment = "positive" if positive_count >= negative_count else "negative" return { "results": results, "overall_sentiment": overall_sentiment, "positive_ratio": round(positive_ratio, 2), "negative_ratio": round(negative_ratio, 2) }