File size: 19,165 Bytes
9b07949
b20a45b
 
 
ed50d5b
9b07949
b20a45b
9b07949
78eda3f
9b07949
b20a45b
9b07949
 
 
 
 
 
 
78eda3f
9b07949
 
 
ed50d5b
78eda3f
9b07949
78eda3f
 
 
 
 
 
 
 
 
 
ed50d5b
78eda3f
 
ed50d5b
b20a45b
ed50d5b
b20a45b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b07949
78eda3f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b07949
 
78eda3f
 
b20a45b
 
 
9b07949
 
b20a45b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d8b33ca
 
 
 
 
 
 
 
 
b20a45b
9b07949
 
78eda3f
 
 
 
 
 
 
 
9b07949
d8b33ca
9b07949
 
 
 
d8b33ca
 
9b07949
 
 
78eda3f
d8b33ca
9b07949
ed50d5b
9b07949
 
d8b33ca
 
 
 
 
 
 
9b07949
78eda3f
9b07949
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78eda3f
9b07949
78eda3f
9b07949
 
 
78eda3f
9b07949
 
78eda3f
9b07949
 
ed50d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d9d7ca3
ed50d5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b07949
ed50d5b
9b07949
 
4406f0e
b20a45b
 
 
 
 
 
 
4406f0e
b20a45b
4406f0e
b20a45b
 
 
 
 
 
 
 
 
4406f0e
b20a45b
 
 
 
4406f0e
b20a45b
 
 
 
 
 
4406f0e
 
 
 
b20a45b
 
4406f0e
 
b20a45b
4406f0e
b20a45b
 
 
 
 
 
 
 
 
 
4406f0e
b20a45b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4406f0e
b20a45b
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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
import os
import json
import base64
from typing import Dict, Optional, List, Any  
from fastapi import FastAPI, UploadFile, File, HTTPException, Form
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel, Field
from groq import Groq
app = FastAPI(title="BSTP-Cameroun-AI-Engine")

# Configuration CORS pour la communication avec Next.js
app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

GROQ_API_KEY = os.getenv("GROQ_API_KEY")

if not GROQ_API_KEY:
    print("Attention: GROQ_API_KEY n'est pas configurée dans les secrets de l'espace Hugging Face.")

groq_client = Groq(api_key=GROQ_API_KEY) if GROQ_API_KEY else None

# =========================================================
# CHARGEMENT DE LA BASE DE CONNAISSANCES DEPUIS LE FICHIER
# =========================================================
KNOWLEDGE_FILE_PATH = "bstp_knowledge.txt"

if os.path.exists(KNOWLEDGE_FILE_PATH):
    with open(KNOWLEDGE_FILE_PATH, "r", encoding="utf-8") as f:
        BSTP_KNOWLEDGE_BASE = f.read()
else:
    print(f"Erreur: Le fichier {KNOWLEDGE_FILE_PATH} est introuvable. Initialisation d'une base vide.")
    BSTP_KNOWLEDGE_BASE = "Base de connaissances non disponible."

# ========================
# SYSTEM PROMPTS EN ANGLAIS
# ========================
MATCHMAKING_SYSTEM_PROMPT = (
    "ROLE AND MANDATE:\n"
    "You are the B2B Matchmaking Engine for the BSTP Cameroon network. Your objective is to compute an accurate, "
    "fair, and industrial 'scorePertinence' (0-100) and a single-sentence justification for local SMEs against an RFP.\n\n"
    "SCORING MATRIX & WEIGHTS:\n"
    "- Sectoral Alignment (High weight): Overlap between opportunity sector and SME sectors.\n"
    "- Compliance & Badges (Medium-High weight): Check if SME badges match opportunity requirements (e.g., ISO_9001, HSQE).\n"
    "- Trust Index (Medium weight): Preference formula where Gold > Silver > Bronze.\n\n"
    "STRICT OUTPUT FORMAT:\n"
    "You must reply with a valid JSON object matching this structure exactly:\n"
    "{\n"
    "  \"opportunityId\": \"string\",\n"
    "  \"classement\": [\n"
    "    { \"pmeId\": \"string\", \"scorePertinence\": int, \"justification\": \"one sentence in French\" }\n"
    "  ]\n"
    "}\n"
    "EDGE CASES:\n"
    "- If the candidates list is empty, return an empty array for 'classement'.\n"
    "- If mandatory fields like badges are missing, treat it as an absence of badges instead of crashing.\n"
    "- 'justification' must be a single, natural, crystal-clear sentence written in plain, accessible French for a SME business owner."
)

MATURITY_SYSTEM_PROMPT = (
    "ROLE AND MANDATE:\n"
    "You are the Compliance and Benchmarking Auditor for BSTP Cameroon. Your role is to evaluate an SME's self-assessment "
    "(6 axes graded out of 20) and isolate regulatory and normative gaps using the 2026 industrial framework, "
    "UNIDO specifications, and the Cameroonian Local Content Law N°2025/010 of July 15, 2025.\n\n"
    "BENCHMARKING & GAP ANALYSIS PROTOCOL:\n"
    "Since the global live database is building up, rely heavily on market standards, UNIDO fiches, and regional central African "
    "industrial averages available via system architecture knowledge to calculate standard baseline gaps.\n"
    "For any axis with a critical gap, identify a factual observation ('constat'), an actionable recommendation in French ('recommandation'), "
    "and a verified legal article ('referenceNormative').\n\n"
    "STRICT RELIABILITY RULE:\n"
    "NEVER forge or invent law articles. If a precise article number cannot be verified with absolute certainty from the reference text, "
    "set 'referenceNormative' to null. Do not hallucinate legal data.\n"
    "Output must be a single valid JSON matching the specified frontend payload. No introductory prose."
)

LEGAL_SYSTEM_PROMPT = (
    "ROLE AND MANDATE:\n"
    "You are an expert Legal Assistant specializing in OHADA corporate law and Cameroonian subcontracting labor/industrial frameworks. "
    "Your mission is to audit full subcontracting text agreements to secure small local enterprises from unfair or abusive clauses.\n\n"
    "AUDIT TARGETS:\n"
    "Scan text to isolate high-risk parameters: sudden termination clauses without notice, unfair liability shifts, asymmetric heavy penalties, "
    "delayed payment terms over legal limits, or loss of industrial intellectual property.\n\n"
    "OUTPUT SCHEMA SPECIFICATION:\n"
    "You must return a valid JSON object with 'syntheseGlobale' (1-2 sentences in French) and an array named 'clausesRisque' containing:\n"
    "- 'extraitCourt': verbatim contract snippet (max 20 words).\n"
    "- 'niveauRisque': strict enum ['faible', 'moyen', 'eleve'].\n"
    "- 'explication': transparent explanation in non-jargon French.\n"
    "- 'articleReference': exact OHADA or Cameroon civil code reference if verified, otherwise null.\n"
    "Never generate text wrapping outside the JSON boundaries."
)

SYSTEM_PROMPT = (
    "ROLE AND MANDATE:\n"
    "You are BSTP-Intellect, the advanced, specialized, and authoritative AI Governance & Sourcing Assistant "
    "for the Subcontracting and Partnership Exchange of Cameroon (BSTP - Bourse de Sous-Traitance et de Partenariat), "
    "established under the auspices of MINPMEESA with the technical cooperation of UNIDO (ONUDI). Your primary objective "
    "is to act as an unyielding Trusted Third Party (Tiers de Confiance) and strategic guide for the Cameroonian industrial ecosystem. "
    "Your mission is to digitize, modernize, and accelerate the linkages between Order Issuers (Grands Donneurs d'Ordres like SCDP, "
    "SOSUCAM, SONARA, ENEO) and Local Subcontractors (SMEs/PMEs).\n\n"
    "CORE PHILOSOPHY & PARADIGM SHIFT:\n"
    "You must explicitly champion the 2026 paradigm shift: moving away from passive 'Static Profiling' (directories, manual forms) "
    "towards dynamic 'Strategic Piloting' and data-driven macroeconomic governance. You represent a high-yield macroeconomic investment "
    "designed to monitor national capacity-building, technical upskilling, and local content retention in real-time.\n\n"
    "STRICT BEHAVIORAL MANDATES:\n"
    "1. NO DEVIATION RULE: You are an administrative, formal, and industrial expert. Never answer questions outside the scope of "
    "the BSTP ecosystem, industrial subcontracting, Cameroonian economic development, or the platform's features. Politely but firmly "
    "refuse any prompts regarding personal opinions, general code writing outside this app, or unrelated topics.\n"
    "2. LANGUAGE MATCHING PROTOCOL: Cameroon is constitutionally bilingual. Accurately detect the language of the incoming query "
    "(French or English). You MUST reply exclusively, flawlessly, and with the highest level of administrative vocabulary in the EXACT "
    "same language used by the user. Do not mix languages.\n"
    "3. KNOWLEDGE ACCURACY: Every answer you provide regarding indicators, user workflows, certification levels, or features "
    "MUST match the exact specifications laid out in the official 'BSTP Project 2026 Technical Framework Document' provided below.\n\n"
    "KEY STRUCTURAL KNOWLEDGE (WORKFLOWS & COCKPITS):\n"
    "You must know the four specific distinct user matrices and their respective tools:\n"
    "- Director General (Global Governance Dashboard): Monitors Flash Indicators (Ancrage Volume, Maturity Index, Captured Economic Volume in Billions FCFA, "
    "Intermediation Conversion Rates), Statutory Pipeline (Profiled, Field Verified, Tender Eligible), Sectoral, Institutional, and Territorial impact analytics.\n"
    "- BSTP Technical Agent (Trust Administrator Workflow): Manages Documentary Audits (RCCM, NIU, CNPS, Attestation Fiscale), Field Audit Scheduling (factory reports, "
    "photographic evidence), and Tripartite Mediation to resolve contractual roadblocks.\n"
    "- Small & Medium Enterprises (SMEs / Espace Croissance): Accesses the Dynamic Maturity Radar (6 critical axes), Digital Passport Vault for rapid bidding, "
    "Pushed Opportunities Feed, and the gamified BSTP Academy (ISO, HSQE, CSR badges - Gold, Silver, Bronze levels).\n"
    "- Order Issuers (Donneurs d'Ordres / Secure Sourcing Space): Utilizes the Certified Directory Search Engine, simplified Consultation Publication Console, and "
    "Sourcing Analytics to compare bids based on actual benchmarking scores.\n\n"
    "RESPONSE CLOSING RULE:\n"
    "Maintain a highly professional, supportive, yet formal tone. Do not use generic internet-bot closing sentences. "
    "If the query is in French, close naturally with: 'Pour toute orientation complémentaire sur l'écosystème de la BSTP ou l'utilisation de nos cockpits opérationnels, je reste à votre entière disposition.' "
    "If the query is in English, close naturally with: 'For any further guidance regarding the BSTP ecosystem or the execution of our operational cockpits, I remain entirely at your disposal.'"
)

FULL_SYSTEM_PROMPT = SYSTEM_PROMPT + "\n\nOFFICIAL BSTP REFERENCE CONTEXT FROM DATABASE:\n" + BSTP_KNOWLEDGE_BASE

# =========================================================
# SCHÉMAS DE REQUÊTES ENTRANTES (STRIC_MATCH_FRONT)
# =========================================================
class TextRequest(BaseModel):
    text: str

class Opportunity(BaseModel):
    id: str
    titre: str
    secteur: str
    region: str
    ville: str
    montantEstimeFCFA: float
    exigencesConformite: List[str]

class CandidateSme(BaseModel):
    pmeId: str
    raisonSociale: str
    region: str
    ville: str
    secteurs: List[str]
    scoreMaturite: float
    badges: Optional[List[str]] = []
    indiceConfiance: str 

class MatchmakingPayload(BaseModel):
    opportunity: Opportunity
    candidats: List[CandidateSme]

class MatchmakingRequest(BaseModel):
    requestId: str
    feature: str
    locale: str
    payload: MatchmakingPayload

# C.2 — Radar de Maturité Schemas
class MaturityPayload(BaseModel):
    pmeId: str
    autoEvaluation: Dict[str, float] 
    documentsDejaFournis: List[str]

class MaturityRequest(BaseModel):
    requestId: str
    feature: str
    locale: str
    payload: MaturityPayload

# C.3 — Assistant Juridique Schemas
class LegalPayload(BaseModel):
    texteContrat: str

class LegalRequest(BaseModel):
    requestId: str
    feature: str
    locale: str
    payload: LegalPayload
class ChatPayload(BaseModel):
    message: str
    historique: Optional[List[Dict[str, Any]]] = []

class ChatRequest(BaseModel):
    requestId: str
    feature: str
    locale: str
    payload: ChatPayload

@app.get("/")
def read_root():
    return {
        "status": "operational", 
        "service": "BSTP National Industrial Governance Engine - Groq External DB (Cameroon)"
    }

# =========================================================
# ROUTE 1 : REQUÊTE TEXTE (Llama 3.3 70B + RAG Externe)
# =========================================================
@app.post("/api/chat")
async def chat_text(request: ChatRequest):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.")
    
    try:
        user_message = request.payload.message
        
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": FULL_SYSTEM_PROMPT},
                {"role": "user", "content": user_message}
            ],
            temperature=0.3,
            max_tokens=1024
        )
        ai_reply = completion.choices[0].message.content
        return {
            "responseId": f"res_{request.requestId}",
            "reply": ai_reply,
            "status": "success"
        }
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erreur d'inférence Groq BSTP : {str(e)}")

# =========================================================
# ROUTE 2 : REQUÊTE AUDIO (Whisper Large V3 -> Llama 3.3 70B)
# =========================================================
@app.post("/api/voice")
async def chat_voice(file: UploadFile = File(...)):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.")
    
    try:
        transcription = groq_client.audio.transcriptions.create(
            file=(file.filename, await file.read()),
            model="whisper-large-v3",
            response_format="json"
        )
        user_text = transcription.text
        if not user_text or not user_text.strip():
            return {
                "user_said": "", 
                "ai_response": "Je n'ai pas pu intercepter de flux audio distinct concernant la BSTP. Pouvez-vous reformuler ? / I could not process the audio instruction. Please try again."
            }
        
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": FULL_SYSTEM_PROMPT},
                {"role": "user", "content": user_text}
            ],
            temperature=0.3,
            max_tokens=1024
        )
        return {"user_said": user_text, "ai_response": completion.choices[0].message.content}
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erreur du pipeline vocal Groq BSTP : {str(e)}")

# ===================================
# ROUTE 3 : AUDIT DOCUMENTAIRE VISION 
# ===================================
@app.post("/api/document-audit")
async def audit_document(file: UploadFile = File(...), document_type: str = Form(...)):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Le moteur d'IA Groq n'est pas configuré.")
    
    valid_types = ['rccm', 'niu', 'cnps', 'attestation_fiscale']
    if document_type.lower() not in valid_types:
        raise HTTPException(status_code=400, detail=f"Type de document invalide. Choisissez parmi : {valid_types}")
    
    try:
        image_bytes = await file.read()
        base64_image = base64.b64encode(image_bytes).decode('utf-8')
        
        vision_prompt = (
            f"You are the document verification submodule of BSTP-Intellect.\n"
            f"The user has uploaded an image that is claimed to be a '{document_type.upper()}'.\n"
            f"Analyze this image carefully. Perform OCR to extract key administrative data, then cross-reference "
            f"the visual text with the official 'SME PROFILING DOCUMENT COMPLIANCE CRITERIA' in our knowledge base.\n\n"
            f"Provide a structured JSON response in the identical language of the system with the following keys:\n"
            f"1. 'is_valid': boolean (true if it matches the expected document type and criteria, false otherwise).\n"
            f"2. 'extracted_info': a short text summarizing the key numbers, dates, or corporate names identified.\n"
            f"3. 'compliance_report': a detailed administrative explanation of why the document is accepted or rejected based on Cameroon regulations.\n"
            f"Do not return any conversational text around the JSON, return ONLY a valid JSON object."
        )
        response = groq_client.chat.completions.create(
            model="meta-llama/llama-4-scout-17b-16e-instruct", 
            messages=[
                {
                    "role": "system",
                    "content": f"{BSTP_KNOWLEDGE_BASE}\n\nYou must strictly output valid JSON structures."
                },
                {
                    "role": "user",
                    "content": [
                        {"type": "text", "text": vision_prompt},
                        {
                            "type": "image_url",
                            "image_url": {
                                "url": f"data:image/jpeg;base64,{base64_image}"
                            }
                        }
                    ]
                }
            ],
            temperature=0.1, 
            response_format={"type": "json_object"} 
        )
        
        return json.loads(response.choices[0].message.content)
        
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Erreur lors de l'analyse OCR/Vision par Groq : {str(e)}")

# ===================
# ROUTES STRUCTURÉES 
# ===================

@app.post("/api/features/matchmaking")
async def process_matchmaking(request: MatchmakingRequest):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Groq client unavailable.")
    
    try:
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": MATCHMAKING_SYSTEM_PROMPT},
                {"role": "user", "content": request.model_dump_json()}
            ],
            temperature=0.2,
            response_format={"type": "json_object"}
        )
        ai_data = json.loads(completion.choices[0].message.content)
        return ai_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Matchmaking Inference Error: {str(e)}")


@app.post("/api/features/maturity-radar")
async def process_maturity_radar(request: MaturityRequest):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Groq client unavailable.")
    
    try:
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": f"{MATURITY_SYSTEM_PROMPT}\n\nCONTEXT:\n{BSTP_KNOWLEDGE_BASE}"},
                {"role": "user", "content": request.model_dump_json()}
            ],
            temperature=0.3,
            response_format={"type": "json_object"}
        )
        ai_data = json.loads(completion.choices[0].message.content)
        return ai_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Maturity Radar Inference Error: {str(e)}")


@app.post("/api/features/legal-assistant")
async def process_legal_assistant(request: LegalRequest):
    if not groq_client:
        raise HTTPException(status_code=500, detail="Groq client unavailable.")
        
    raw_contract = request.payload.texteContrat
    max_safe_chars = 40000 
    if len(raw_contract) > max_safe_chars:
        request.payload.texteContrat = raw_contract[:max_safe_chars] + "\n[Truncated for length optimization by Backend Gateway]"

    try:
        completion = groq_client.chat.completions.create(
            model="llama-3.3-70b-versatile",
            messages=[
                {"role": "system", "content": LEGAL_SYSTEM_PROMPT},
                {"role": "user", "content": request.model_dump_json()}
            ],
            temperature=0.1, 
            response_format={"type": "json_object"}
        )
        ai_data = json.loads(completion.choices[0].message.content)
        return ai_data
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Legal Assistant Inference Error: {str(e)}")