feat: Generation Page AI workflows + AI/Vector modules + exam session fixes

Generation Page (complete rebuild):
- Full production-parity exam generation wizard with 4 IELTS modules
- Reading: AI passage gen, 5 exercise types (MCQ, Fill, Write, T/F, Match)
- Listening: 4 section types, AI context gen, TTS audio gen (ElevenLabs)
- Writing: Task 1/2, AI instruction gen, word limits, marks
- Speaking: 3 parts, AI script gen, avatar video gen (7 avatars)
- Per-module config: timer, CEFR difficulty, access, approval, rubrics
- Exam submission workflow (draft/published)

Exam Structures:
- New encoach.exam.structure model + CRUD controller
- ExamStructuresPage wired to real API

AI Module (encoach_ai):
- OpenAI service, ElevenLabs TTS, AWS Polly, ELAI avatars
- AI settings model with Odoo config parameters
- 7 generation endpoints (passage, exercises, instructions, scripts, context)

Vector Module (encoach_vector):
- pgvector integration for RAG-based content search
- Embedding service with sentence-transformers

Exam Session Fixes:
- Fixed ExamSession.tsx field mapping (question_type→type, exam_title→title)
- Fixed submit payload to include attempt_id and answers
- Fixed normalizeType to handle null/undefined

Tested: 12/12 API tests passed, browser-verified with real OpenAI calls
Made-with: Cursor
This commit is contained in:
Yamen Ahmad
2026-04-11 14:27:03 +04:00
parent 0c8443256d
commit 6a62a43d61
34 changed files with 2261 additions and 77 deletions

View File

@@ -5,7 +5,7 @@
'summary': 'Exam scoring, grading queue, feedback, and score release management',
'author': 'EnCoach',
'license': 'LGPL-3',
'depends': ['encoach_core', 'encoach_exam_template', 'encoach_course_gen', 'encoach_resources'],
'depends': ['encoach_core', 'encoach_exam_template', 'encoach_course_gen', 'encoach_resources', 'encoach_ai'],
'data': [
'security/ir.model.access.csv',
'views/student_attempt_views.xml',

View File

@@ -338,34 +338,52 @@ class EncoachGradingController(http.Controller):
student_response = ans.answer if ans else ''
suggested_score = question.marks * 0.5
suggested_feedback = (
f"AI suggestion for {question.skill} {question.question_type} question. "
f"Student provided a response of {len(student_response)} characters. "
f"Suggested mid-range score based on rubric criteria."
)
confidence = 0.6
if not student_response:
suggested_score = 0.0
suggested_feedback = "No response provided by student."
confidence = 0.95
return _json_response({
'suggested_score': 0.0,
'suggested_feedback': 'No response provided by student.',
'confidence': 0.95,
})
rubric = None
rubric_text = "IELTS Band Descriptors"
if attempt.exam_id and attempt.exam_id.template_id:
Rubric = request.env['encoach.rubric'].sudo()
rubric = Rubric.search([
('skill', '=', question.skill),
], limit=1)
rubric_rec = Rubric.search([('skill', '=', question.skill)], limit=1)
if rubric_rec:
rubric_text = rubric_rec.name
if rubric:
suggested_feedback += f" Rubric '{rubric.name}' criteria should be applied."
return _json_response({
'suggested_score': round(suggested_score, 1),
'suggested_feedback': suggested_feedback,
'confidence': confidence,
})
try:
from odoo.addons.encoach_ai.services.openai_service import OpenAIService
ai = OpenAIService(request.env)
skill = question.skill or 'writing'
if skill in ('speaking',):
result = ai.grade_speaking(rubric_text, student_response)
else:
result = ai.grade_writing(
rubric_text,
question.body or question.name or '',
student_response,
)
overall = result.get('overall_band', 0)
suggested_score = min(overall / 9.0 * question.marks, question.marks)
return _json_response({
'suggested_score': round(suggested_score, 1),
'suggested_feedback': result.get('feedback', ''),
'confidence': 0.85,
'scores': result.get('scores', {}),
'suggestions': result.get('suggestions', []),
})
except Exception as ai_err:
_logger.warning('AI grading unavailable, using heuristic: %s', ai_err)
suggested_score = question.marks * 0.5
return _json_response({
'suggested_score': round(suggested_score, 1),
'suggested_feedback': (
f"AI grading unavailable ({ai_err}). "
f"Heuristic: mid-range score for {len(student_response)} char response."
),
'confidence': 0.4,
})
except Exception as e:
_logger.exception('ai_suggest failed')

View File

@@ -1,67 +1,60 @@
"""AI-powered speaking assessment using encoach_ai services."""
import logging
_logger = logging.getLogger(__name__)
class SpeakingEvaluator:
"""AI-powered speaking assessment using Whisper + GPT."""
"""AI-powered speaking assessment using Whisper + GPT via encoach_ai."""
def __init__(self, env=None):
self.env = env
def transcribe_audio(self, audio_path_or_bytes):
"""Transcribe audio using the encoach_ai WhisperService."""
try:
from odoo.addons.encoach_ai.services.whisper_service import WhisperService
whisper = WhisperService(self.env)
if isinstance(audio_path_or_bytes, (bytes, bytearray)):
return whisper.transcribe(audio_path_or_bytes, use_api=True)
with open(audio_path_or_bytes, "rb") as f:
return whisper.transcribe(f.read(), use_api=True)
except ImportError:
_logger.warning("encoach_ai not installed, falling back to direct whisper")
return self._fallback_transcribe(audio_path_or_bytes)
except Exception as e:
_logger.error("Transcription error: %s", e)
return {"text": "", "language": "en", "segments": [], "error": str(e)}
def evaluate_speaking(self, transcription, rubric_criteria, target_band=6.0):
"""Evaluate speaking using encoach_ai OpenAIService."""
try:
from odoo.addons.encoach_ai.services.openai_service import OpenAIService
ai = OpenAIService(self.env)
result = ai.grade_speaking(
f"Target Band: {target_band}\n{rubric_criteria}",
transcription,
)
return result
except ImportError:
_logger.warning("encoach_ai not installed")
return {"overall_band": 0, "feedback": "AI evaluation not available"}
except Exception as e:
_logger.error("Speaking evaluation error: %s", e)
return {"overall_band": 0, "feedback": f"Evaluation error: {e}"}
@staticmethod
def transcribe_audio(audio_path):
"""Transcribe audio using Whisper."""
def _fallback_transcribe(audio_path):
"""Direct whisper fallback if encoach_ai is not available."""
try:
import whisper
model = whisper.load_model("base")
result = model.transcribe(audio_path)
return {
'text': result['text'],
'language': result.get('language', 'en'),
'segments': result.get('segments', []),
"text": result["text"],
"language": result.get("language", "en"),
"segments": result.get("segments", []),
}
except ImportError:
_logger.warning("whisper not installed")
return {'text': '', 'language': 'en', 'segments': [], 'error': 'Whisper not available'}
@staticmethod
def evaluate_speaking(transcription, rubric_criteria, target_band=6.0):
"""Evaluate speaking using OpenAI GPT."""
try:
import openai
prompt = (
"You are an IELTS speaking examiner. Evaluate the following speaking response.\n\n"
f"Target Band: {target_band}\n\n"
f"Rubric Criteria:\n{rubric_criteria}\n\n"
f"Transcription:\n{transcription}\n\n"
"Provide scores for each criterion (0-9 scale) and detailed feedback.\n"
"Return JSON format:\n"
"{\n"
' "fluency_coherence": {"score": X, "feedback": "..."},\n'
' "lexical_resource": {"score": X, "feedback": "..."},\n'
' "grammatical_range": {"score": X, "feedback": "..."},\n'
' "pronunciation": {"score": X, "feedback": "..."},\n'
' "overall_band": X,\n'
' "general_feedback": "..."\n'
"}"
)
client = openai.OpenAI()
response = client.chat.completions.create(
model="gpt-4",
messages=[
{"role": "system", "content": "You are an expert IELTS speaking examiner."},
{"role": "user", "content": prompt},
],
temperature=0.3,
)
import json
result = json.loads(response.choices[0].message.content)
return result
except ImportError:
_logger.warning("openai not installed")
return {'overall_band': 0, 'general_feedback': 'AI evaluation not available', 'error': 'OpenAI not available'}
except Exception as e:
_logger.error("Speaking evaluation error: %s", e)
return {'overall_band': 0, 'general_feedback': f'Evaluation error: {e}'}
return {"text": "", "language": "en", "segments": [], "error": "Whisper not available"}