Spaces:
Runtime error

File size: 6,782 Bytes
46085c7
 
e1e0ef6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ea64cf1
e1e0ef6
ea64cf1
779f136
46085c7
 
 
 
 
 
 
2c50191
46085c7
00033cb
46085c7
 
 
 
 
 
 
 
 
 
 
00033cb
46085c7
 
779f136
ea64cf1
 
 
 
00033cb
ea64cf1
00033cb
 
ea64cf1
 
 
 
 
 
 
 
 
46085c7
 
 
 
 
 
 
 
 
 
 
00033cb
 
 
 
 
 
46085c7
 
 
 
 
 
 
00033cb
 
 
 
327ea2d
00033cb
46085c7
327ea2d
 
 
 
 
 
00033cb
 
 
 
 
 
 
 
 
 
 
779f136
00033cb
 
 
 
 
 
46085c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c50191
46085c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c50191
46085c7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c50191
46085c7
 
 
 
 
5f2a085
 
 
 
 
 
 
46085c7
 
 
 
 
 
 
 
2c50191
46085c7
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
from __future__ import annotations

import socket

# Save the original getaddrinfo
_original_getaddrinfo = socket.getaddrinfo

def _patched_getaddrinfo(*args, **kwargs):
    # Determine the family requested
    family = socket.AF_UNSPEC
    if 'family' in kwargs:
        family = kwargs['family']
    elif len(args) > 2:
        family = args[2]
        
    responses = _original_getaddrinfo(*args, **kwargs)
    
    # If the user asked for AF_UNSPEC, filter out AF_INET6
    if family == socket.AF_UNSPEC:
        return [r for r in responses if r[0] != socket.AF_INET6]
    return responses

socket.getaddrinfo = _patched_getaddrinfo

from contextlib import asynccontextmanager

from collections.abc import AsyncIterator
import logging
from uuid import uuid4

from fastapi import Depends, FastAPI, HTTPException, Query, Request, status
from fastapi.middleware.cors import CORSMiddleware
from sqlalchemy.ext.asyncio import AsyncSession

from app.core.config import get_settings
from app.core.security import AuthContext, require_internal_token, require_moderator_token
from app.db import get_session
from app.ml.factory import create_text_scorer
from app.queues import RabbitMQBroker
from app.repository import get_incident, list_alerts, list_incidents, update_incident
from app.schemas import (
    AlertListResponse,
    AnalyzeTextRequest,
    AnalyzeTextResponse,
    IncidentListResponse,
    IncidentRead,
    IncidentUpdateRequest,
    InferenceTask,
)
from app.services.moderation import process_text_direct

settings = get_settings()
logger = logging.getLogger(__name__)


@asynccontextmanager
async def lifespan(app: FastAPI) -> AsyncIterator[None]:
    if settings.pipeline_mode == "queue" and not hasattr(app.state, "broker"):
        app.state.broker = RabbitMQBroker(settings)
    if settings.pipeline_mode == "direct" and not hasattr(app.state, "scorer"):
        app.state.scorer = create_text_scorer(settings)
    try:
        yield
    finally:
        broker: RabbitMQBroker | None = getattr(app.state, "broker", None)
        if broker:
            await broker.close()


app = FastAPI(title="Cybully Moderation API", version="0.1.0", lifespan=lifespan)
app.add_middleware(
    CORSMiddleware,
    allow_origins=settings.allowed_cors_origins,
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)


@app.get("/health")
async def health() -> dict[str, str]:
    return {
        "status": "ok",
        "environment": settings.environment,
        "pipeline_mode": settings.pipeline_mode,
        "scorer_provider": settings.scorer_provider,
    }


@app.post(
    "/api/v1/analyze/text",
    response_model=AnalyzeTextResponse,
    status_code=status.HTTP_202_ACCEPTED,
)
async def analyze_text(
    request: Request,
    payload: AnalyzeTextRequest,
    session: AsyncSession = Depends(get_session),
    auth: AuthContext = Depends(require_internal_token),
) -> AnalyzeTextResponse:
    incident_id = str(uuid4())
    task_payload = payload.model_dump()
    if auth.auth_mode == "supabase":
        # With Supabase auth, do not trust caller-supplied user_id.
        task_payload["user_id"] = auth.user_id or payload.user_id

    task = InferenceTask(incident_id=incident_id, **task_payload)

    if settings.pipeline_mode == "direct":
        scorer = getattr(request.app.state, "scorer", create_text_scorer(settings))
        try:
            await process_text_direct(
                task=task,
                session=session,
                settings=settings,
                scorer=scorer,
            )
        except Exception as exc:
            logger.exception("Direct moderation processing failed for incident %s", incident_id)
            raise HTTPException(
                status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
                detail="Direct moderation processing failed.",
            ) from exc
        return AnalyzeTextResponse(tracking_id=incident_id)

    broker: RabbitMQBroker = request.app.state.broker
    try:
        await broker.publish_json(settings.inference_task_queue, task.model_dump(mode="json"))
    except Exception as exc:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail="Inference queue is unavailable.",
        ) from exc
    return AnalyzeTextResponse(tracking_id=incident_id)


@app.get(
    "/api/v1/incidents",
    response_model=IncidentListResponse,
)
async def get_incidents(
    _auth: AuthContext = Depends(require_moderator_token),
    session: AsyncSession = Depends(get_session),
    severity: str | None = Query(default=None, pattern="^(low|medium|high)$"),
    status_filter: str | None = Query(default=None, alias="status"),
    limit: int = Query(default=25, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
) -> IncidentListResponse:
    items, total = await list_incidents(
        session,
        severity=severity,
        status=status_filter,
        limit=limit,
        offset=offset,
    )
    return IncidentListResponse(items=[IncidentRead.model_validate(item) for item in items], total=total, limit=limit, offset=offset)


@app.get(
    "/api/v1/incidents/{incident_id}",
    response_model=IncidentRead,
)
async def get_incident_detail(
    incident_id: str,
    _auth: AuthContext = Depends(require_moderator_token),
    session: AsyncSession = Depends(get_session),
) -> IncidentRead:
    incident = await get_incident(session, incident_id)
    if not incident:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Incident not found.")
    return IncidentRead.model_validate(incident)


@app.patch(
    "/api/v1/incidents/{incident_id}",
    response_model=IncidentRead,
)
async def patch_incident(
    incident_id: str,
    payload: IncidentUpdateRequest,
    auth: AuthContext = Depends(require_moderator_token),
    session: AsyncSession = Depends(get_session),
) -> IncidentRead:
    incident = await get_incident(session, incident_id)
    if not incident:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Incident not found.")
    updated = await update_incident(
        session,
        incident,
        payload,
        reviewer_user_id=auth.user_id,
        reviewer_email=auth.email,
    )
    return IncidentRead.model_validate(updated)


@app.get(
    "/api/v1/alerts",
    response_model=AlertListResponse,
)
async def get_alerts(
    _auth: AuthContext = Depends(require_moderator_token),
    session: AsyncSession = Depends(get_session),
    limit: int = Query(default=25, ge=1, le=100),
    offset: int = Query(default=0, ge=0),
) -> AlertListResponse:
    items, total = await list_alerts(session, limit=limit, offset=offset)
    return AlertListResponse(items=items, total=total, limit=limit, offset=offset)