Update main.py
Browse files
main.py
CHANGED
|
@@ -0,0 +1,116 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
from fastapi import FastAPI, UploadFile, File, HTTPException
|
| 3 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 4 |
+
from pydantic import BaseModel
|
| 5 |
+
from groq import Groq
|
| 6 |
+
|
| 7 |
+
app = FastAPI(title="BSTP-Cameroun")
|
| 8 |
+
|
| 9 |
+
# Configuration CORS pour permettre à ton application Vue.js de communiquer librement avec l'API
|
| 10 |
+
app.add_middleware(
|
| 11 |
+
CORSMiddleware,
|
| 12 |
+
allow_origins=["*"],
|
| 13 |
+
allow_credentials=True,
|
| 14 |
+
allow_methods=["*"],
|
| 15 |
+
allow_headers=["*"],
|
| 16 |
+
)
|
| 17 |
+
GROQ_API_KEY = os.getenv("GROQ_API_KEY")
|
| 18 |
+
|
| 19 |
+
if not GROQ_API_KEY:
|
| 20 |
+
print("⚠️ Attention: GROQ_API_KEY n'est pas configurée dans les secrets.")
|
| 21 |
+
groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None
|
| 22 |
+
# Prompt système bilingue, adaptatif et optimisé pour les fins de phrases
|
| 23 |
+
SYSTEM_PROMPT = (
|
| 24 |
+
"You are SafeBot, a specialized emergency cyber-psychologist and crisis counseling expert "
|
| 25 |
+
"for the SafeChild platform in Cameroon. Your primary directive is to offer immediate, warm, "
|
| 26 |
+
"deeply empathetic, and calming psychological first aid to parents, families, or children "
|
| 27 |
+
"experiencing severe distress, abuse, cyberbullying, or child disappearance.\n\n"
|
| 28 |
+
"CRITICAL BEHAVIORAL MANDATES:\n"
|
| 29 |
+
"1. LANGUAGE MATCHING: Cameroon is bilingual. Accurately detect the user's language (French or English). "
|
| 30 |
+
"You MUST reply exclusively and flawlessly in the EXACT same language used by the user. Never mix languages.\n"
|
| 31 |
+
"2. PSYCHOLOGICAL POSTURE: Use validating, active listening, and non-judgmental language. De-escalate "
|
| 32 |
+
"panic immediately. Your tone is supportive, warm, yet highly clear and structured.\n"
|
| 33 |
+
"3. CAMEROON PROTECTION & SIGNALING PROTOCOL: When a critical abuse, violence, or child abduction case is reported, "
|
| 34 |
+
"you must provide immediate safety actions and actively guide the user to official Cameroonian entities and local NGO networks:\n"
|
| 35 |
+
" - State Institutions: MINPROFF (Ministère de la Promotion de la Femme et de la Famille), MINAS (Ministère des Affaires Sociales), "
|
| 36 |
+
"or dedicated security units like the Judicial Police (Police Judiciaire) and Gendarmerie Territorial Brigades.\n"
|
| 37 |
+
" - Key NGOs & Support: UNICEF Cameroon, ALVF (Association de Lutte contre les Violences faites aux Femmes) which is highly active in local protection, "
|
| 38 |
+
"and community legal assistance networks.\n"
|
| 39 |
+
"4. CAMEROON CRITICAL EMERGENCY NUMBERS: Always prominently display these specific lines when a situation requires intervention:\n"
|
| 40 |
+
" - Police Secours / Emergency: 117 (or 1500 for the Gendarmerie Nationale hotline)\n"
|
| 41 |
+
" - Child Protection Hotline (Ligne Verte): 116 (dedicated number for reporting child abuse/rights violations)\n"
|
| 42 |
+
" - Violence Against Women & Families Hotline: 8142 (MINPROFF dedicated toll-free line)\n"
|
| 43 |
+
" - Fire & Emergency Rescue (Sapeurs-Pompiers): 118\n"
|
| 44 |
+
"5. NO FORMAL DIAGNOSIS: Do not state formal clinical or legal judgments. Position yourself as an urgent "
|
| 45 |
+
"psychological compass designed to protect the child and guide the family toward specialized real-world Cameroonian infrastructure.\n"
|
| 46 |
+
"6. MESSAGE CLOSING RULE: Never end your messages with repetitive or robotic questions like 'How can I help you today?'. "
|
| 47 |
+
"Instead, close your answers naturally and warmly. "
|
| 48 |
+
"If the user is text-chatting, use smooth closing sentences like: 'Si vous avez d'autres questions ou si vous souhaitez approfondir un point, n'hésitez pas, je suis là.' "
|
| 49 |
+
"If the user is speaking in English, use: 'If you have any other questions, please do not hesitate to ask, I am right here for you.'"
|
| 50 |
+
)
|
| 51 |
+
|
| 52 |
+
class TextRequest(BaseModel):
|
| 53 |
+
text: str
|
| 54 |
+
|
| 55 |
+
@app.get("/")
|
| 56 |
+
def read_root():
|
| 57 |
+
return {"status": "operational", "service": "SafeChild SafeBot AI Engine - Groq Dedicated (Cameroon Bilingual)"}
|
| 58 |
+
@app.post("/api/chat")
|
| 59 |
+
async def chat_text(request: TextRequest):
|
| 60 |
+
if not groq_client:
|
| 61 |
+
raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.")
|
| 62 |
+
|
| 63 |
+
try:
|
| 64 |
+
completion = groq_client.chat.completions.create(
|
| 65 |
+
model="llama-3.3-70b-versatile",
|
| 66 |
+
messages=[
|
| 67 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 68 |
+
{"role": "user", "content": request.text}
|
| 69 |
+
],
|
| 70 |
+
temperature=0.5,
|
| 71 |
+
max_tokens=1024
|
| 72 |
+
)
|
| 73 |
+
return {"ai_response": completion.choices[0].message.content}
|
| 74 |
+
except Exception as e:
|
| 75 |
+
raise HTTPException(status_code=500, detail=f"Erreur d'inférence Groq : {str(e)}")
|
| 76 |
+
|
| 77 |
+
# =========================================================
|
| 78 |
+
# ROUTE 2 : REQUÊTE AUDIO (Whisper Large V3 -> Llama 3.3 70B)
|
| 79 |
+
# =========================================================
|
| 80 |
+
@app.post("/api/voice")
|
| 81 |
+
async def chat_voice(file: UploadFile = File(...)):
|
| 82 |
+
if not groq_client:
|
| 83 |
+
raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.")
|
| 84 |
+
|
| 85 |
+
try:
|
| 86 |
+
# Étape A : Transcription de la note vocale (Français / Anglais du Cameroun détectés automatiquement)
|
| 87 |
+
transcription = groq_client.audio.transcriptions.create(
|
| 88 |
+
file=(file.filename, await file.read()),
|
| 89 |
+
model="whisper-large-v3",
|
| 90 |
+
response_format="json"
|
| 91 |
+
)
|
| 92 |
+
|
| 93 |
+
user_text = transcription.text
|
| 94 |
+
|
| 95 |
+
if not user_text or not user_text.strip():
|
| 96 |
+
return {
|
| 97 |
+
"user_said": "",
|
| 98 |
+
"ai_response": "Je n'ai pas pu décoder de voix distincte sur cet enregistrement. Pouvez-vous réessayer ? / I could not clearly understand the audio. Could you please try again?"
|
| 99 |
+
}
|
| 100 |
+
completion = groq_client.chat.completions.create(
|
| 101 |
+
model="llama-3.3-70b-versatile",
|
| 102 |
+
messages=[
|
| 103 |
+
{"role": "system", "content": SYSTEM_PROMPT},
|
| 104 |
+
{"role": "user", "content": user_text}
|
| 105 |
+
],
|
| 106 |
+
temperature=0.5,
|
| 107 |
+
max_tokens=1024
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
return {
|
| 111 |
+
"user_said": user_text,
|
| 112 |
+
"ai_response": completion.choices[0].message.content
|
| 113 |
+
}
|
| 114 |
+
|
| 115 |
+
except Exception as e:
|
| 116 |
+
raise HTTPException(status_code=500, detail=f"Erreur du pipeline vocal Groq : {str(e)}")
|