Local User commited on
Commit ·
6e4bbd4
1
Parent(s): cd95514
added AI plugin for sentiment and summarize endpoints
Browse files- app/main.py +3 -0
- app/services/sentiment.py +131 -21
- app/services/summarize.py +63 -4
- requirements.txt +2 -0
app/main.py
CHANGED
|
@@ -5,6 +5,7 @@ import sys
|
|
| 5 |
|
| 6 |
import structlog
|
| 7 |
from fastapi import FastAPI
|
|
|
|
| 8 |
|
| 9 |
from app.routes import api_router
|
| 10 |
|
|
@@ -29,6 +30,8 @@ def configure_logging() -> None:
|
|
| 29 |
|
| 30 |
|
| 31 |
def create_app() -> FastAPI:
|
|
|
|
|
|
|
| 32 |
configure_logging()
|
| 33 |
app = FastAPI(title="Summarize & Sentiment API")
|
| 34 |
app.include_router(api_router)
|
|
|
|
| 5 |
|
| 6 |
import structlog
|
| 7 |
from fastapi import FastAPI
|
| 8 |
+
from dotenv import load_dotenv
|
| 9 |
|
| 10 |
from app.routes import api_router
|
| 11 |
|
|
|
|
| 30 |
|
| 31 |
|
| 32 |
def create_app() -> FastAPI:
|
| 33 |
+
# Load environment variables from a local .env file for development.
|
| 34 |
+
load_dotenv()
|
| 35 |
configure_logging()
|
| 36 |
app = FastAPI(title="Summarize & Sentiment API")
|
| 37 |
app.include_router(api_router)
|
app/services/sentiment.py
CHANGED
|
@@ -1,28 +1,138 @@
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 3 |
from app.schemas.models import SentimentLabel, SentimentResponse
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
-
def _analyze_sentiment(text: str) -> SentimentResponse:
|
| 7 |
-
"""Placeholder heuristic; swap for a model or API as needed."""
|
| 8 |
-
lower = text.lower()
|
| 9 |
-
positive_hits = sum(1 for w in ("good", "great", "love", "excellent", "happy") if w in lower)
|
| 10 |
-
negative_hits = sum(1 for w in ("bad", "hate", "awful", "terrible", "sad") if w in lower)
|
| 11 |
-
|
| 12 |
-
if positive_hits > negative_hits:
|
| 13 |
-
return SentimentResponse(
|
| 14 |
-
sentiment=SentimentLabel.POSITIVE,
|
| 15 |
-
confidence=0.75,
|
| 16 |
-
explanation="More positive cue words than negative (placeholder).",
|
| 17 |
-
)
|
| 18 |
-
if negative_hits > positive_hits:
|
| 19 |
-
return SentimentResponse(
|
| 20 |
-
sentiment=SentimentLabel.NEGATIVE,
|
| 21 |
-
confidence=0.75,
|
| 22 |
-
explanation="More negative cue words than positive (placeholder).",
|
| 23 |
-
)
|
| 24 |
return SentimentResponse(
|
| 25 |
-
sentiment=
|
| 26 |
-
confidence=
|
| 27 |
-
explanation=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 28 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
from __future__ import annotations
|
| 2 |
|
| 3 |
+
import json
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from openai import OpenAI
|
| 9 |
+
from dotenv import load_dotenv
|
| 10 |
+
|
| 11 |
from app.schemas.models import SentimentLabel, SentimentResponse
|
| 12 |
|
| 13 |
+
_DEFAULT_MODEL = "gpt-4.1-mini"
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
def _normalize_sentiment_label(value: str) -> SentimentLabel:
|
| 17 |
+
"""Map common model sentiment variants to supported labels."""
|
| 18 |
+
normalized = re.sub(r"[^a-z]+", "_", value.strip().lower()).strip("_")
|
| 19 |
+
if not normalized:
|
| 20 |
+
raise RuntimeError("Invalid sentiment label returned by model")
|
| 21 |
+
|
| 22 |
+
if normalized in {"positive", "pos", "somewhat_positive", "very_positive"}:
|
| 23 |
+
return SentimentLabel.POSITIVE
|
| 24 |
+
if normalized in {"negative", "neg", "somewhat_negative", "very_negative"}:
|
| 25 |
+
return SentimentLabel.NEGATIVE
|
| 26 |
+
if normalized in {"neutral", "mixed", "mixed_sentiment", "balanced"}:
|
| 27 |
+
return SentimentLabel.NEUTRAL
|
| 28 |
+
|
| 29 |
+
if "positive" in normalized:
|
| 30 |
+
return SentimentLabel.POSITIVE
|
| 31 |
+
if "negative" in normalized:
|
| 32 |
+
return SentimentLabel.NEGATIVE
|
| 33 |
+
if "neutral" in normalized or "mixed" in normalized:
|
| 34 |
+
return SentimentLabel.NEUTRAL
|
| 35 |
+
|
| 36 |
+
raise RuntimeError("Invalid sentiment label returned by model")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def _extract_text_from_response(response: Any) -> str:
|
| 40 |
+
"""Extract assistant text from OpenAI responses API output."""
|
| 41 |
+
output = getattr(response, "output", None) or []
|
| 42 |
+
chunks: list[str] = []
|
| 43 |
+
|
| 44 |
+
for item in output:
|
| 45 |
+
if getattr(item, "type", None) != "message":
|
| 46 |
+
continue
|
| 47 |
+
for content_part in getattr(item, "content", None) or []:
|
| 48 |
+
if getattr(content_part, "type", None) == "output_text":
|
| 49 |
+
text = getattr(content_part, "text", "")
|
| 50 |
+
if text:
|
| 51 |
+
chunks.append(text)
|
| 52 |
+
|
| 53 |
+
return "\n".join(chunks).strip()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def _parse_sentiment_response(raw_text: str) -> SentimentResponse:
|
| 57 |
+
"""Parse and validate model JSON output."""
|
| 58 |
+
candidate = raw_text.strip()
|
| 59 |
+
if candidate.startswith("```"):
|
| 60 |
+
candidate = re.sub(r"^```(?:json)?\s*", "", candidate, flags=re.IGNORECASE)
|
| 61 |
+
candidate = re.sub(r"\s*```$", "", candidate)
|
| 62 |
+
|
| 63 |
+
# If extra text is present, recover the first JSON object.
|
| 64 |
+
if "{" in candidate and "}" in candidate:
|
| 65 |
+
first = candidate.find("{")
|
| 66 |
+
last = candidate.rfind("}")
|
| 67 |
+
candidate = candidate[first : last + 1]
|
| 68 |
+
|
| 69 |
+
try:
|
| 70 |
+
payload = json.loads(candidate)
|
| 71 |
+
except json.JSONDecodeError as exc:
|
| 72 |
+
raise RuntimeError("Model did not return valid JSON for sentiment output") from exc
|
| 73 |
+
|
| 74 |
+
if not isinstance(payload, dict):
|
| 75 |
+
raise RuntimeError("Model response must be a JSON object")
|
| 76 |
+
|
| 77 |
+
sentiment_raw = str(payload.get("sentiment", ""))
|
| 78 |
+
sentiment = _normalize_sentiment_label(sentiment_raw)
|
| 79 |
+
|
| 80 |
+
confidence_raw = payload.get("confidence")
|
| 81 |
+
try:
|
| 82 |
+
confidence = float(confidence_raw)
|
| 83 |
+
except (TypeError, ValueError) as exc:
|
| 84 |
+
raise RuntimeError("Invalid confidence value returned by model") from exc
|
| 85 |
+
|
| 86 |
+
if confidence < 0.0 or confidence > 1.0:
|
| 87 |
+
raise RuntimeError("Confidence must be between 0.0 and 1.0")
|
| 88 |
+
|
| 89 |
+
explanation_raw = payload.get("explanation")
|
| 90 |
+
if not isinstance(explanation_raw, str) or not explanation_raw.strip():
|
| 91 |
+
raise RuntimeError("Explanation must be a non-empty string")
|
| 92 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 93 |
return SentimentResponse(
|
| 94 |
+
sentiment=sentiment,
|
| 95 |
+
confidence=confidence,
|
| 96 |
+
explanation=explanation_raw.strip(),
|
| 97 |
+
)
|
| 98 |
+
|
| 99 |
+
|
| 100 |
+
def _analyze_sentiment(text: str) -> SentimentResponse:
|
| 101 |
+
"""Analyze sentiment with OpenAI and return strict JSON fields."""
|
| 102 |
+
load_dotenv()
|
| 103 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 104 |
+
if not api_key:
|
| 105 |
+
raise RuntimeError("OPENAI_API_KEY is not set")
|
| 106 |
+
|
| 107 |
+
model = os.getenv("OPENAI_MODEL", _DEFAULT_MODEL)
|
| 108 |
+
client = OpenAI(api_key=api_key)
|
| 109 |
+
|
| 110 |
+
response = client.responses.create(
|
| 111 |
+
model=model,
|
| 112 |
+
temperature=0,
|
| 113 |
+
input=[
|
| 114 |
+
{
|
| 115 |
+
"role": "system",
|
| 116 |
+
"content": (
|
| 117 |
+
"You are a senior developer sentiment analysis assistant. "
|
| 118 |
+
"Analyze sentiment and respond with strict JSON only."
|
| 119 |
+
),
|
| 120 |
+
},
|
| 121 |
+
{
|
| 122 |
+
"role": "user",
|
| 123 |
+
"content": (
|
| 124 |
+
"Analyze the sentiment of the text entered in JSON. "
|
| 125 |
+
"Respond only in JSON with keys: sentiment, confidence, explanation. "
|
| 126 |
+
"The sentiment value must be exactly one of: positive, negative, neutral. "
|
| 127 |
+
"No extra text.\n\n"
|
| 128 |
+
f"Text:\n{text}"
|
| 129 |
+
),
|
| 130 |
+
},
|
| 131 |
+
],
|
| 132 |
)
|
| 133 |
+
|
| 134 |
+
raw_output = _extract_text_from_response(response)
|
| 135 |
+
if not raw_output:
|
| 136 |
+
raise RuntimeError("No sentiment analysis returned from model")
|
| 137 |
+
|
| 138 |
+
return _parse_sentiment_response(raw_output)
|
app/services/summarize.py
CHANGED
|
@@ -1,5 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
def _get_summary(text: str, max_length: int) -> str:
|
| 2 |
-
"""
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from openai import OpenAI
|
| 7 |
+
from dotenv import load_dotenv
|
| 8 |
+
|
| 9 |
+
_DEFAULT_MODEL = "gpt-4.1-mini"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _extract_text_from_response(response: Any) -> str:
|
| 13 |
+
"""Extract assistant text from OpenAI responses API output."""
|
| 14 |
+
output = getattr(response, "output", None) or []
|
| 15 |
+
chunks: list[str] = []
|
| 16 |
+
|
| 17 |
+
for item in output:
|
| 18 |
+
if getattr(item, "type", None) != "message":
|
| 19 |
+
continue
|
| 20 |
+
for content_part in getattr(item, "content", None) or []:
|
| 21 |
+
if getattr(content_part, "type", None) == "output_text":
|
| 22 |
+
text = getattr(content_part, "text", "")
|
| 23 |
+
if text:
|
| 24 |
+
chunks.append(text)
|
| 25 |
+
|
| 26 |
+
return "\n".join(chunks).strip()
|
| 27 |
+
|
| 28 |
+
|
| 29 |
def _get_summary(text: str, max_length: int) -> str:
|
| 30 |
+
"""Generate concise summary text with an OpenAI model."""
|
| 31 |
+
load_dotenv()
|
| 32 |
+
api_key = os.getenv("OPENAI_API_KEY")
|
| 33 |
+
if not api_key:
|
| 34 |
+
raise RuntimeError("OPENAI_API_KEY is not set")
|
| 35 |
+
|
| 36 |
+
model = os.getenv("OPENAI_MODEL", _DEFAULT_MODEL)
|
| 37 |
+
client = OpenAI(api_key=api_key)
|
| 38 |
+
|
| 39 |
+
response = client.responses.create(
|
| 40 |
+
model=model,
|
| 41 |
+
temperature=0,
|
| 42 |
+
input=[
|
| 43 |
+
{
|
| 44 |
+
"role": "system",
|
| 45 |
+
"content": (
|
| 46 |
+
"You are a concise summarization assistant. "
|
| 47 |
+
"Return only the summary text with no preamble."
|
| 48 |
+
),
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"role": "user",
|
| 52 |
+
"content": (
|
| 53 |
+
f"Summarize the text entered in JSON in under {max_length} words. "
|
| 54 |
+
"Return only the summary, no extra commentary.\n\n"
|
| 55 |
+
f"Text:\n{text}"
|
| 56 |
+
),
|
| 57 |
+
},
|
| 58 |
+
],
|
| 59 |
+
)
|
| 60 |
+
|
| 61 |
+
summary = _extract_text_from_response(response)
|
| 62 |
+
if not summary:
|
| 63 |
+
raise RuntimeError("No summary text returned from model")
|
| 64 |
+
return summary
|
requirements.txt
CHANGED
|
@@ -2,3 +2,5 @@ fastapi>=0.115.0
|
|
| 2 |
uvicorn[standard]>=0.32.0
|
| 3 |
pydantic>=2.10.0
|
| 4 |
structlog>=24.4.0
|
|
|
|
|
|
|
|
|
| 2 |
uvicorn[standard]>=0.32.0
|
| 3 |
pydantic>=2.10.0
|
| 4 |
structlog>=24.4.0
|
| 5 |
+
openai>=1.75.0
|
| 6 |
+
python-dotenv>=1.0.1
|