"""Cyrus Language Ultimate Brain — Vercel single-file serverless function. Keys from env vars: LANGUAGE_APP_KEY (gate), GEMINI_API_KEY (AI). DB in /tmp (ephemeral on serverless).""" import os import sqlite3 import json import struct import logging from fastapi import FastAPI, HTTPException, Depends, Request from fastapi.responses import Response, JSONResponse from fastapi.middleware.cors import CORSMiddleware from fastapi.security import APIKeyHeader from pydantic import BaseModel, Field logging.basicConfig(level=logging.INFO, format='%(asctime)s - 🧠 [UltimateBrain] - %(message)s') API_KEY_NAME = "X-App-Key" api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=True) def _gate_key() -> str: return os.environ.get("LANGUAGE_APP_KEY", "") async def verify_api_key(api_key: str = Depends(api_key_header)): expected = _gate_key() if not expected: raise HTTPException(status_code=500, detail="Server misconfigured: LANGUAGE_APP_KEY is not set.") if api_key != expected: raise HTTPException(status_code=401, detail="دسترسی غیرمجاز! کلید امنیتی نامعتبر است.") return api_key class ChatRequest(BaseModel): user_id: str = Field(..., example="student_101") user_message: str = Field(..., example="Yesterday I go to the store and buyed two apple.") class TtsRequest(BaseModel): text: str = Field(..., example="think") slow: bool = Field(default=False, description="Speak slowly and clearly (drills slow-listen).") class VocabularyItem(BaseModel): word: str = Field(description="A more advanced or natural vocabulary word related to the user's input.") persian_meaning: str = Field(description="Persian translation of the word.") example_sentence: str = Field(description="A short English example sentence using this word.") class GrammarAnalysis(BaseModel): has_error: bool = Field(description="True if the user made ANY grammar, spelling, or syntax mistake.") error_category: str = Field(description="The category of the error (e.g., 'Prepositions', 'Verb Tense'). Return 'None' if no error.") corrected_sentence: str = Field(description="The fully corrected version of the user's message.") persian_explanation: str = Field(description="A warm, encouraging Persian explanation of the mistakes and how to fix them.") class LanguageAppResponse(BaseModel): ai_reply: str = Field(description="The natural, friendly English response from Ava, the conversation partner, to keep the conversation going. Pure conversation only: it must NEVER correct the learner or comment on their mistakes.") grammar_analysis: GrammarAnalysis vocabulary_boost: list[VocabularyItem] = Field(description="List of 1 to 2 vocabulary suggestions to upgrade their English.") estimated_cefr_level: str = Field(description="Estimate the user's CEFR level (A1, A2, B1, B2, C1, C2) based on this message.") engagement_score: int = Field(description="Score from 1 to 10 evaluating how much detail the user provided in their message.") def _wav_wrap(pcm: bytes, rate: int, channels: int = 1, bits: int = 16) -> bytes: """Wrap raw little-endian PCM in a minimal RIFF/WAVE header.""" byte_rate = rate * channels * bits // 8 block_align = channels * bits // 8 header = b"RIFF" + struct.pack(" wav bytes; per warm instance self._init_memory() def _get_client(self): if self._client is None: from google import genai api_key = os.environ.get("GEMINI_API_KEY", "") if not api_key: raise RuntimeError("GEMINI_API_KEY is not set on the server.") self._client = genai.Client(api_key=api_key) return self._client def _init_memory(self): conn = sqlite3.connect(self.db_path) cursor = conn.cursor() cursor.execute(''' CREATE TABLE IF NOT EXISTS student_profiles ( user_id TEXT PRIMARY KEY, current_cefr_level TEXT DEFAULT 'A1', grammar_weaknesses TEXT DEFAULT '[]', total_interactions INTEGER DEFAULT 0 ) ''') conn.commit() conn.close() def process_message(self, user_id: str, message: str) -> dict: from google.genai import types profile = self._get_profile(user_id) system_instruction = ( "You are Ava, a friendly English conversation partner for a Persian-speaking learner. " "Your ONLY job in ai_reply is to CHAT: listen, understand the meaning, react warmly to the CONTENT of what " "they said, and keep the conversation going with a natural follow-up question. " "NEVER correct the learner in ai_reply: no grammar fixes, no vocabulary fixes, no pronunciation notes, " "no quoting their sentence back with corrections, no 'you should say...', and no teaching notes of any kind. " "If their English has mistakes, simply understand them and answer — you may naturally use a correct form " "inside your own reply as ordinary conversation, but never point it out, highlight it, or explain it. " "Keep ai_reply short, warm and clear, with simple English matched to the learner's level. " "Reply in English; use simple Persian only if the learner writes in Persian or asks for Persian help. " "ONLY exception: if the learner's message itself explicitly asks to be corrected (for example 'correct me', " "'check my mistakes', or 'اشتباهامو بگو'), then in this reply only you may gently mention the main mistake. " "The grammar_analysis, vocabulary_boost, estimated_cefr_level and engagement_score fields are SILENT " "background data for the app's separate practice features (a mistakes list and a quiz the learner opens " "on purpose) — keep filling them in accurately as before, but they must never leak into ai_reply. " "Return the data exactly matching the requested JSON schema." ) prompt = ( f"[Student ID: {user_id}]\n" f"Historical Estimated Level: {profile['level']}\n" f"Known Weaknesses: {profile['weaknesses']}\n\n" f"Student Message: {message}" ) try: client = self._get_client() response = client.models.generate_content( model=self.model_name, contents=prompt, config=types.GenerateContentConfig( system_instruction=system_instruction, temperature=0.3, max_output_tokens=800, thinking_config=types.ThinkingConfig(thinking_budget=0), response_mime_type="application/json", response_schema=LanguageAppResponse, ), ) result_data = json.loads(response.text.strip()) grammar_data = result_data.get("grammar_analysis", {}) if grammar_data.get("has_error") and grammar_data.get("error_category") != "None": self._update_profile(user_id, grammar_data["error_category"], result_data.get("estimated_cefr_level", profile['level'])) return result_data except Exception as e: logging.error(f"AI Error: {str(e)}") return {"error": str(e)} def transcribe_audio(self, audio: bytes, mime: str) -> str: """Transcribe a short voice clip with Gemini (same approach as the tour backend). The pages record with MediaRecorder inside the app WebView, where SpeechRecognition does not exist, and post the raw audio here. Returns the transcript text ('' when no clear speech).""" from google.genai import types prompt = ("Transcribe the speech in this audio clip exactly, word for word, " "in the language that is spoken. Return ONLY the transcript text: " "no quotes, no labels, no commentary. If there is no clear speech, " "return an empty string.") part = types.Part.from_bytes(data=audio, mime_type=mime) client = self._get_client() last_err = None for model in (self.model_name, "gemini-3.5-flash-lite"): try: response = client.models.generate_content( model=model, contents=[part, prompt], config=types.GenerateContentConfig( temperature=0, max_output_tokens=256, thinking_config=types.ThinkingConfig(thinking_budget=0), ), ) text = (response.text or "").strip() # The model sometimes wraps an empty result in quotes — normalize. if text in ('""', "''"): text = "" return text except Exception as e: last_err = e logging.error(f"Transcribe error ({model}): {str(e)}") continue raise RuntimeError(f"Failed to transcribe audio: {last_err}") def synthesize_speech(self, text: str, slow: bool) -> bytes: """Server-side TTS for the academy app (Android WebView has no usable speechSynthesis voice on some devices). Gemini TTS returns raw 16-bit PCM; wrap it in a WAV header so any