File size: 2,632 Bytes
c726703
 
 
 
 
 
 
7e493b0
c726703
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
51d338a
 
 
 
7e493b0
 
 
 
 
 
 
 
 
 
 
 
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
import os
from fastapi import Depends, FastAPI, Header, HTTPException
from fastapi.middleware.cors import CORSMiddleware
import spaces

from ai_engine import AIEngine
from config import Config
from models import EscutarPayload, EscutarResponse, FeedbackPayload, FeedbackResponse

app = FastAPI(
    title="Plenitude — Cerebro Negra Plena",
    description="API de atendimento da pastelaria Negra Plena com suporte a GPU.",
    version="1.0.1",
)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_methods=["*"],
    allow_headers=["*"],
)

engine = AIEngine()


def require_token(authorization: str = Header(default="")) -> None:
    if not Config.API_AUTH_TOKEN:
        return
    expected = f"Bearer {Config.API_AUTH_TOKEN}"
    if authorization != expected:
        raise HTTPException(status_code=401, detail="Token invalido")


# A Hugging Face exige que haja uma funcao com @spaces.GPU se o Space tiver GPU!
@spaces.GPU
def run_ml_task(texto: str):
    return f"GPU Processed: {texto}"


@app.get("/")
def root():
    return {
        "assistente": Config.ASSISTANT_NAME,
        "empresa": Config.COMPANY_NAME,
        "status": "ok",
        "provedor": Config.get_active_provider(),
        "gpu_enabled": True
    }


@app.get("/health")
@app.get("/api/health")
def health():
    return {"status": "ok"}


@app.post("/escutar", response_model=EscutarResponse)
@app.post("/api/escutar", response_model=EscutarResponse)
def escutar(payload: EscutarPayload, _: None = Depends(require_token)):
    cliente = payload.numero_crm or payload.numero or "unknown"
    texto = payload.texto.strip()
    
    if not texto and not payload.audio_base64:
        return EscutarResponse(
            texto="Nao consegui ler a sua mensagem. Pode escrever de novo, por favor?"
        )

    if not texto and payload.audio_base64:
        texto = "(o cliente enviou um audio; transcricao na GPU ainda em preparacao)"

    resposta, mensagem_id = engine.responder(
        cliente, texto, payload.nome or "Cliente",
        fora_expediente=payload.fora_expediente,
    )
    return EscutarResponse(texto=resposta, mensagem_id=mensagem_id)


@app.post("/feedback", response_model=FeedbackResponse)
@app.post("/api/feedback", response_model=FeedbackResponse)
def feedback(payload: FeedbackPayload, _: None = Depends(require_token)):
    ok = engine.learning.rate(
        payload.mensagem_id, payload.nota, payload.comentario or ""
    )
    if ok:
        return FeedbackResponse(ok=True, detalhe="Avaliação registada. Obrigado!")
    return FeedbackResponse(ok=False, detalhe="mensagem_id não encontrado.")