ERNEST2002/Playbook-Grading-OS
0
1import os2import json3import logging4import re5import google.generativeai as genai6import requests7 8# ==========================================9# ENTERPRISE CLOUD BRAIN (HYBRID: GEMINI + DEEPSEEK)10# ==========================================11logging.basicConfig(filename="logs/brain_router.log", level=logging.INFO, 12 format="%(asctime)s - HYBRID BRAIN - %(levelname)s - %(message)s")13 14# GEMINI (KWA AJILI YA VISION TU - Haipo hapa, ipo kwenye Orchestrator)15# DEEPSEEK (KWA AJILI YA REASONING, GRADING NA CHATBOT)16DEEPSEEK_API_KEY = "sk-9cbbcf7ee6904655908d445edf3ea874"17DEEPSEEK_URL = "https://api.deepseek.com/v1/chat/completions"18 19class PlaybookVoiceEngine:20 def __init__(self):21 self.system_manual = """22 Your name is PLAYBOOK AI. You are an omniscient system guide for a grading software.23 NEVER mention the name "DeepSeek" or "OpenAI" or "Gemini" under any circumstances.24 You have access to real-time grading data and system interface details.25 If a user asks about a student's score, use the provided database context to explain exactly why they got that score based on the scheme.26 Keep answers short, professional, and directly related to the user's query.27 """28 29 def ask_system_agent(self, user_query, db_context=""):30 prompt = f"""31 [SYSTEM DATABASE CONTEXT]:32 {db_context if db_context else 'No specific context provided. Assume general system inquiry.'}33 34 [USER QUESTION]:35 {user_query}36 """37 38 headers = {39 "Content-Type": "application/json",40 "Authorization": f"Bearer {DEEPSEEK_API_KEY}"41 }42 43 payload = {44 "model": "deepseek-chat", # Tunatumia Chat model kwa spidi na bei nafuu kwenye maongezi45 "messages": [46 {"role": "system", "content": self.system_manual},47 {"role": "user", "content": prompt}48 ],49 "temperature": 0.350 }51 52 try:53 response = requests.post(DEEPSEEK_URL, headers=headers, json=payload)54 response.raise_for_status()55 data = response.json()56 return data['choices'][0]['message']['content'].strip()57 except Exception as e:58 logging.error(f"Playbook Agent Error: {e}")59 return "Connection to Playbook Brain interrupted. Please try again."60 61class PlaybookReasoning:62 def __init__(self):63 self.headers = {64 "Content-Type": "application/json",65 "Authorization": f"Bearer {DEEPSEEK_API_KEY}"66 }67 68 def _clean_json(self, raw_text):69 text = raw_text.strip()70 if text.startswith("```json"): text = text[7:]71 elif text.startswith("```"): text = text[3:]72 if text.endswith("```"): text = text[:-3]73 return json.loads(text.strip())74 75 def grade_answer(self, ocr_text, marking_scheme, max_score=100):76 logging.info("Routing logic to PLAYBOOK REASONING CORE (DeepSeek)...")77 78 system_prompt = """79 You are PLAYBOOK AI, an elite Professor-level academic grading system and data extractor. 80 NEVER mention 'DeepSeek' in your response. Output STRICTLY AND ONLY VALID JSON.81 """82 83 user_prompt = f"""84 Max Exam Score: {max_score}85 86 MARKING SCHEME & CALIBRATION MATRIX:87 {marking_scheme}88 89 STUDENT ANSWER DOSSIER (OCR Text): 90 {ocr_text}91 92 YOUR MISSIONS:93 MISSION 1: VALIDATION (Anti-Garbage Guardrail)94 - Check if the OCR text looks like an academic exam, quiz, assignment, or scheme.95 - If it looks like an ID card (NIDA), birth certificate, random news article, or completely irrelevant garbage, DO NOT GRADE IT.96 - Set "flag" to "RED", score to 0, and output "SYSTEM HALT: This document does not appear to be an academic script." in the overall_explanation.97 98 MISSION 2: IDENTITY EXTRACTION99 - Look closely for the student's Name or Registration Number/ID at the top of the script.100 - If found, put it in the "detected_identity" field.101 - If absolutely no name or ID is found, output "UNKNOWN SCRIPT - NEEDS REVIEW".102 103 MISSION 3: GRADING (Only if Validation Passes)104 1. Analyze the student's answer strictly against the provided scheme.105 2. Give partial marks if methods/steps are correct as per calibration.106 3. For EVERY question, provide a detailed "reason" for marks AND "advice".107 4. If it explicitly says "[MISSING_ANSWER]", award 0 marks.108 109 Output ONLY valid JSON without markdown, matching this EXACT schema:110 {{111 "detected_identity": "Name or Reg No found, or 'UNKNOWN SCRIPT - NEEDS REVIEW'",112 "is_valid_exam": true/false,113 "total_score": 0,114 "overall_explanation": "Detailed paragraph explaining overall academic performance OR the rejection reason.",115 "confidence": 95,116 "flag": "GREEN" or "RED",117 "breakdown": {{118 "Q1": {{"score": 0, "reason": "Detailed remark on performance AND specific advice for improvement."}}119 }},120 "recommendations": "Actionable overall study advice."121 }}122 """123 124 payload = {125 "model": "deepseek-reasoner", # Tunatumia Reasoner (R1) kwa ajili ya kufikiri kwa kina (Deep Thinking)126 "messages": [127 {"role": "system", "content": system_prompt},128 {"role": "user", "content": user_prompt}129 ],130 "temperature": 0.1131 }132 133 try:134 response = requests.post(DEEPSEEK_URL, headers=self.headers, json=payload)135 response.raise_for_status()136 data = response.json()137 # Tunachukua content tu (Tuna-ignore 'reasoning_content' ya R1 ili tupate Json safi)138 final_text = data['choices'][0]['message']['content']139 return self._clean_json(final_text)140 except Exception as e:141 logging.error(f"Playbook Grading Error: {e}")142 return self._fallback_error_json("Playbook AI failed to process this script. Check connection.")143 144 def simulate_what_if(self, original_breakdown_json, adjustment_command):145 system_prompt = "You are PLAYBOOK AI, an advanced grading simulator. Output STRICTLY JSON without markdown."146 user_prompt = f"""147 Original Breakdown JSON: {original_breakdown_json}148 Teacher's Command: "{adjustment_command}"149 Apply the command to the original breakdown. 150 Schema: {{"new_total": 0, "new_breakdown": {{}}}}151 """152 153 payload = {154 "model": "deepseek-chat",155 "messages": [156 {"role": "system", "content": system_prompt},157 {"role": "user", "content": user_prompt}158 ],159 "temperature": 0.1160 }161 162 try:163 response = requests.post(DEEPSEEK_URL, headers=self.headers, json=payload)164 response.raise_for_status()165 data = response.json()166 return self._clean_json(data['choices'][0]['message']['content'])167 except Exception as e:168 logging.error(f"Simulation Error: {e}")169 return {"error": "Simulation failed via Playbook AI."}170 171 def _fallback_error_json(self, error_msg):172 return {173 "detected_identity": "SYSTEM ERROR",174 "is_valid_exam": False,175 "total_score": 0, 176 "overall_explanation": error_msg, 177 "confidence": 0, 178 "flag": "RED",179 "breakdown": {}, 180 "recommendations": "Please review manually."181 }182 183class PlaybookMasterRouter:184 def __init__(self):185 self.voice = PlaybookVoiceEngine()186 self.reasoning = PlaybookReasoning()187 188 def boot_sequence(self):189 logging.info("System Booted. Playbook Enterprise AI (DeepSeek R1 + Chat) Active.")190 191if __name__ == "__main__":192 p = PlaybookMasterRouter()193 p.boot_sequence()