Initial commit
This commit is contained in:
15
backend/Dockerfile
Normal file
15
backend/Dockerfile
Normal file
@@ -0,0 +1,15 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1
|
||||
|
||||
RUN apt-get update && apt-get install -y gcc libpq-dev && rm -rf /var/lib/apt/lists/*
|
||||
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r /app/requirements.txt
|
||||
|
||||
COPY . /app
|
||||
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000", "--reload"]
|
||||
BIN
backend/app/__pycache__/curriculum.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/curriculum.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/__pycache__/database.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/database.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/__pycache__/main.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/main.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/__pycache__/models.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/models.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/__pycache__/schemas.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/schemas.cpython-313.pyc
Normal file
Binary file not shown.
BIN
backend/app/__pycache__/services.cpython-313.pyc
Normal file
BIN
backend/app/__pycache__/services.cpython-313.pyc
Normal file
Binary file not shown.
53
backend/app/curriculum.py
Normal file
53
backend/app/curriculum.py
Normal file
@@ -0,0 +1,53 @@
|
||||
SKILLS = [
|
||||
{
|
||||
"code": "math_addition_posee",
|
||||
"subject": "Mathématiques",
|
||||
"label": "Addition posée à deux chiffres",
|
||||
"description": "Savoir additionner des nombres entiers à deux chiffres.",
|
||||
},
|
||||
{
|
||||
"code": "math_tables_x3_x4",
|
||||
"subject": "Mathématiques",
|
||||
"label": "Tables de multiplication 3 et 4",
|
||||
"description": "Connaître et utiliser les tables de 3 et de 4.",
|
||||
},
|
||||
{
|
||||
"code": "fr_conjugaison_present",
|
||||
"subject": "Français",
|
||||
"label": "Présent des verbes du 1er groupe",
|
||||
"description": "Conjuguer un verbe du premier groupe au présent.",
|
||||
},
|
||||
{
|
||||
"code": "fr_nature_mots",
|
||||
"subject": "Français",
|
||||
"label": "Identifier nom, verbe et adjectif",
|
||||
"description": "Reconnaître la nature simple de mots dans une phrase.",
|
||||
},
|
||||
]
|
||||
|
||||
QUESTIONS = {
|
||||
"math_addition_posee": {
|
||||
"question": "Calcule 27 + 35.",
|
||||
"expected_answer": "62",
|
||||
"feedback_ok": "Bravo, 27 + 35 = 62. Tu as bien additionné les dizaines et les unités.",
|
||||
"feedback_ko": "La bonne réponse était 62. Pense à additionner d'abord les unités puis les dizaines.",
|
||||
},
|
||||
"math_tables_x3_x4": {
|
||||
"question": "Combien font 4 × 6 ?",
|
||||
"expected_answer": "24",
|
||||
"feedback_ok": "Oui, 4 fois 6 font 24. Très bien.",
|
||||
"feedback_ko": "La bonne réponse était 24. Tu peux réciter la table de 4 : 4, 8, 12, 16, 20, 24.",
|
||||
},
|
||||
"fr_conjugaison_present": {
|
||||
"question": "Conjugue le verbe 'chanter' avec 'nous' au présent.",
|
||||
"expected_answer": "nous chantons",
|
||||
"feedback_ok": "Très bien, on dit bien 'nous chantons'.",
|
||||
"feedback_ko": "La bonne réponse était 'nous chantons'. Avec 'nous', beaucoup de verbes du 1er groupe finissent par -ons.",
|
||||
},
|
||||
"fr_nature_mots": {
|
||||
"question": "Dans la phrase 'Le chat noir dort', quel est l'adjectif ?",
|
||||
"expected_answer": "noir",
|
||||
"feedback_ok": "Oui, 'noir' décrit le chat, c'est donc l'adjectif.",
|
||||
"feedback_ko": "La bonne réponse était 'noir'. Un adjectif donne une précision sur le nom.",
|
||||
},
|
||||
}
|
||||
17
backend/app/database.py
Normal file
17
backend/app/database.py
Normal file
@@ -0,0 +1,17 @@
|
||||
import os
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import declarative_base, sessionmaker
|
||||
|
||||
DATABASE_URL = os.getenv("DATABASE_URL", "sqlite:///./local.db")
|
||||
|
||||
engine = create_engine(DATABASE_URL, pool_pre_ping=True)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
def get_db():
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
144
backend/app/main.py
Normal file
144
backend/app/main.py
Normal file
@@ -0,0 +1,144 @@
|
||||
from contextlib import asynccontextmanager
|
||||
from fastapi import Depends, FastAPI, HTTPException
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from sqlalchemy.orm import Session
|
||||
from .database import Base, engine, get_db
|
||||
from . import models, schemas
|
||||
from .curriculum import QUESTIONS
|
||||
from .services import build_llm_reply, ensure_student_mastery, evaluate_answer, pick_next_skill, seed_skills
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app: FastAPI):
|
||||
Base.metadata.create_all(bind=engine)
|
||||
db = next(get_db())
|
||||
try:
|
||||
seed_skills(db)
|
||||
finally:
|
||||
db.close()
|
||||
yield
|
||||
|
||||
|
||||
app = FastAPI(title="Professeur Virtuel API", version="0.1.0", lifespan=lifespan)
|
||||
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=[
|
||||
"https://prof.open-squared.tech",
|
||||
"http://localhost:3000",
|
||||
"http://localhost:3001",
|
||||
],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
@app.get("/health")
|
||||
def health():
|
||||
return {"status": "ok"}
|
||||
|
||||
|
||||
@app.get("/students", response_model=list[schemas.StudentRead])
|
||||
def list_students(db: Session = Depends(get_db)):
|
||||
return db.query(models.Student).order_by(models.Student.id.asc()).all()
|
||||
|
||||
|
||||
@app.post("/students", response_model=schemas.StudentRead)
|
||||
def create_student(payload: schemas.StudentCreate, db: Session = Depends(get_db)):
|
||||
student = models.Student(**payload.model_dump())
|
||||
db.add(student)
|
||||
db.commit()
|
||||
db.refresh(student)
|
||||
ensure_student_mastery(db, student)
|
||||
return student
|
||||
|
||||
|
||||
@app.post("/session/start", response_model=schemas.ChatResponse)
|
||||
def start_session(student_id: int, db: Session = Depends(get_db)):
|
||||
student = db.query(models.Student).filter_by(id=student_id).first()
|
||||
if not student:
|
||||
raise HTTPException(status_code=404, detail="Élève introuvable")
|
||||
|
||||
ensure_student_mastery(db, student)
|
||||
message = (
|
||||
f"Bonjour {student.first_name} ! Je suis ton professeur virtuel. "
|
||||
"Aujourd'hui, on va apprendre pas à pas et faire un petit test pour voir ce que tu maîtrises déjà."
|
||||
)
|
||||
db.add(models.Message(student_id=student.id, role="assistant", content=message))
|
||||
db.commit()
|
||||
return schemas.ChatResponse(reply=message)
|
||||
|
||||
|
||||
@app.post("/chat", response_model=schemas.ChatResponse)
|
||||
def chat(payload: schemas.ChatRequest, db: Session = Depends(get_db)):
|
||||
student = db.query(models.Student).filter_by(id=payload.student_id).first()
|
||||
if not student:
|
||||
raise HTTPException(status_code=404, detail="Élève introuvable")
|
||||
|
||||
db.add(models.Message(student_id=student.id, role="user", content=payload.message))
|
||||
db.commit()
|
||||
|
||||
reply = build_llm_reply(db, payload.student_id, payload.message)
|
||||
|
||||
db.add(models.Message(student_id=student.id, role="assistant", content=reply))
|
||||
db.commit()
|
||||
return schemas.ChatResponse(reply=reply)
|
||||
|
||||
|
||||
@app.get("/progress/{student_id}", response_model=schemas.ProgressResponse)
|
||||
def get_progress(student_id: int, db: Session = Depends(get_db)):
|
||||
student = db.query(models.Student).filter_by(id=student_id).first()
|
||||
if not student:
|
||||
raise HTTPException(status_code=404, detail="Élève introuvable")
|
||||
|
||||
rows = (
|
||||
db.query(models.StudentSkillMastery, models.Skill)
|
||||
.join(models.Skill, models.Skill.id == models.StudentSkillMastery.skill_id)
|
||||
.filter(models.StudentSkillMastery.student_id == student_id)
|
||||
.order_by(models.Skill.subject.asc(), models.Skill.label.asc())
|
||||
.all()
|
||||
)
|
||||
progress = [
|
||||
schemas.SkillProgress(
|
||||
code=skill.code,
|
||||
subject=skill.subject,
|
||||
label=skill.label,
|
||||
mastery_score=mastery.mastery_score,
|
||||
confidence=mastery.confidence,
|
||||
evidence_count=mastery.evidence_count,
|
||||
)
|
||||
for mastery, skill in rows
|
||||
]
|
||||
return schemas.ProgressResponse(student=student, progress=progress)
|
||||
|
||||
|
||||
@app.get("/assessment/next/{student_id}", response_model=schemas.AssessmentQuestionResponse)
|
||||
def next_assessment(student_id: int, db: Session = Depends(get_db)):
|
||||
student = db.query(models.Student).filter_by(id=student_id).first()
|
||||
if not student:
|
||||
raise HTTPException(status_code=404, detail="Élève introuvable")
|
||||
skill = pick_next_skill(db, student_id)
|
||||
question = QUESTIONS[skill.code]["question"]
|
||||
return schemas.AssessmentQuestionResponse(skill_code=skill.code, skill_label=skill.label, question=question)
|
||||
|
||||
|
||||
@app.post("/assessment/answer", response_model=schemas.AssessmentAnswerResponse)
|
||||
def answer_assessment(payload: schemas.AssessmentAnswerRequest, db: Session = Depends(get_db)):
|
||||
student = db.query(models.Student).filter_by(id=payload.student_id).first()
|
||||
if not student:
|
||||
raise HTTPException(status_code=404, detail="Élève introuvable")
|
||||
if payload.skill_code not in QUESTIONS:
|
||||
raise HTTPException(status_code=400, detail="Compétence inconnue")
|
||||
|
||||
correct, feedback, mastery_score = evaluate_answer(
|
||||
db, payload.student_id, payload.skill_code, payload.answer
|
||||
)
|
||||
db.add(models.Message(student_id=student.id, role="assistant", content=feedback))
|
||||
db.commit()
|
||||
return schemas.AssessmentAnswerResponse(
|
||||
correct=correct,
|
||||
feedback=feedback,
|
||||
mastery_score=mastery_score,
|
||||
)
|
||||
69
backend/app/models.py
Normal file
69
backend/app/models.py
Normal file
@@ -0,0 +1,69 @@
|
||||
from datetime import datetime
|
||||
from sqlalchemy import DateTime, Float, ForeignKey, Integer, String, Text, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column, relationship
|
||||
from .database import Base
|
||||
|
||||
|
||||
class Student(Base):
|
||||
__tablename__ = "students"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True, index=True)
|
||||
first_name: Mapped[str] = mapped_column(String(100))
|
||||
age: Mapped[int] = mapped_column(Integer)
|
||||
grade: Mapped[str] = mapped_column(String(50))
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
||||
|
||||
messages = relationship("Message", back_populates="student", cascade="all, delete-orphan")
|
||||
mastery = relationship("StudentSkillMastery", back_populates="student", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class Message(Base):
|
||||
__tablename__ = "messages"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
student_id: Mapped[int] = mapped_column(ForeignKey("students.id"), index=True)
|
||||
role: Mapped[str] = mapped_column(String(20))
|
||||
content: Mapped[str] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
||||
|
||||
student = relationship("Student", back_populates="messages")
|
||||
|
||||
|
||||
class Skill(Base):
|
||||
__tablename__ = "skills"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
code: Mapped[str] = mapped_column(String(100), unique=True)
|
||||
subject: Mapped[str] = mapped_column(String(50))
|
||||
label: Mapped[str] = mapped_column(String(255))
|
||||
description: Mapped[str] = mapped_column(Text)
|
||||
|
||||
|
||||
class StudentSkillMastery(Base):
|
||||
__tablename__ = "student_skill_mastery"
|
||||
__table_args__ = (UniqueConstraint("student_id", "skill_id", name="uq_student_skill"),)
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
student_id: Mapped[int] = mapped_column(ForeignKey("students.id"), index=True)
|
||||
skill_id: Mapped[int] = mapped_column(ForeignKey("skills.id"), index=True)
|
||||
mastery_score: Mapped[float] = mapped_column(Float, default=50.0)
|
||||
confidence: Mapped[float] = mapped_column(Float, default=0.2)
|
||||
evidence_count: Mapped[int] = mapped_column(Integer, default=0)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow)
|
||||
|
||||
student = relationship("Student", back_populates="mastery")
|
||||
skill = relationship("Skill")
|
||||
|
||||
|
||||
class AssessmentAttempt(Base):
|
||||
__tablename__ = "assessment_attempts"
|
||||
|
||||
id: Mapped[int] = mapped_column(Integer, primary_key=True)
|
||||
student_id: Mapped[int] = mapped_column(ForeignKey("students.id"), index=True)
|
||||
skill_code: Mapped[str] = mapped_column(String(100), index=True)
|
||||
question: Mapped[str] = mapped_column(Text)
|
||||
expected_answer: Mapped[str] = mapped_column(Text)
|
||||
student_answer: Mapped[str] = mapped_column(Text)
|
||||
is_correct: Mapped[int] = mapped_column(Integer)
|
||||
feedback: Mapped[str] = mapped_column(Text)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime, default=datetime.utcnow)
|
||||
60
backend/app/schemas.py
Normal file
60
backend/app/schemas.py
Normal file
@@ -0,0 +1,60 @@
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import List
|
||||
|
||||
|
||||
class StudentCreate(BaseModel):
|
||||
first_name: str = Field(..., min_length=1)
|
||||
age: int = Field(..., ge=8, le=12)
|
||||
grade: str
|
||||
|
||||
|
||||
class StudentRead(BaseModel):
|
||||
id: int
|
||||
first_name: str
|
||||
age: int
|
||||
grade: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ChatRequest(BaseModel):
|
||||
student_id: int
|
||||
message: str
|
||||
|
||||
|
||||
class ChatResponse(BaseModel):
|
||||
reply: str
|
||||
should_speak: bool = True
|
||||
|
||||
|
||||
class SkillProgress(BaseModel):
|
||||
code: str
|
||||
subject: str
|
||||
label: str
|
||||
mastery_score: float
|
||||
confidence: float
|
||||
evidence_count: int
|
||||
|
||||
|
||||
class ProgressResponse(BaseModel):
|
||||
student: StudentRead
|
||||
progress: List[SkillProgress]
|
||||
|
||||
|
||||
class AssessmentQuestionResponse(BaseModel):
|
||||
skill_code: str
|
||||
skill_label: str
|
||||
question: str
|
||||
|
||||
|
||||
class AssessmentAnswerRequest(BaseModel):
|
||||
student_id: int
|
||||
skill_code: str
|
||||
answer: str
|
||||
|
||||
|
||||
class AssessmentAnswerResponse(BaseModel):
|
||||
correct: bool
|
||||
feedback: str
|
||||
mastery_score: float
|
||||
138
backend/app/services.py
Normal file
138
backend/app/services.py
Normal file
@@ -0,0 +1,138 @@
|
||||
import os
|
||||
from typing import List
|
||||
from openai import OpenAI
|
||||
from sqlalchemy.orm import Session
|
||||
from . import models
|
||||
from .curriculum import QUESTIONS, SKILLS
|
||||
|
||||
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
||||
|
||||
|
||||
SYSTEM_PROMPT = """
|
||||
Tu es ProfAmi, un professeur virtuel français pour enfants de 8 à 12 ans.
|
||||
Règles :
|
||||
- Tu parles toujours en français simple et chaleureux.
|
||||
- Tu donnes des explications très courtes, puis un mini exemple.
|
||||
- Tu tiens compte du niveau de l'élève et de ses faiblesses indiquées dans le contexte.
|
||||
- Tu n'inventes pas la progression : elle est fournie dans le contexte.
|
||||
- Tu encourages sans infantiliser.
|
||||
- Quand l'élève se trompe, tu expliques calmement puis proposes une question très simple.
|
||||
- Tu enseignes principalement le programme national français niveau primaire/cycle 3.
|
||||
""".strip()
|
||||
|
||||
|
||||
def seed_skills(db: Session) -> None:
|
||||
for skill in SKILLS:
|
||||
existing = db.query(models.Skill).filter(models.Skill.code == skill["code"]).first()
|
||||
if not existing:
|
||||
db.add(models.Skill(**skill))
|
||||
db.commit()
|
||||
|
||||
|
||||
def ensure_student_mastery(db: Session, student: models.Student) -> None:
|
||||
all_skills = db.query(models.Skill).all()
|
||||
for skill in all_skills:
|
||||
found = (
|
||||
db.query(models.StudentSkillMastery)
|
||||
.filter_by(student_id=student.id, skill_id=skill.id)
|
||||
.first()
|
||||
)
|
||||
if not found:
|
||||
db.add(models.StudentSkillMastery(student_id=student.id, skill_id=skill.id))
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_student_context(db: Session, student_id: int) -> str:
|
||||
student = db.query(models.Student).filter_by(id=student_id).first()
|
||||
mastery = (
|
||||
db.query(models.StudentSkillMastery, models.Skill)
|
||||
.join(models.Skill, models.Skill.id == models.StudentSkillMastery.skill_id)
|
||||
.filter(models.StudentSkillMastery.student_id == student_id)
|
||||
.all()
|
||||
)
|
||||
recent_messages = (
|
||||
db.query(models.Message)
|
||||
.filter_by(student_id=student_id)
|
||||
.order_by(models.Message.created_at.desc())
|
||||
.limit(6)
|
||||
.all()
|
||||
)
|
||||
|
||||
lines: List[str] = [
|
||||
f"Élève: {student.first_name}, {student.age} ans, classe {student.grade}.",
|
||||
"Progression par compétence:",
|
||||
]
|
||||
for mastery_row, skill in mastery:
|
||||
lines.append(
|
||||
f"- {skill.label}: score={mastery_row.mastery_score:.1f}, confiance={mastery_row.confidence:.2f}, preuves={mastery_row.evidence_count}"
|
||||
)
|
||||
lines.append("Historique récent:")
|
||||
for message in reversed(recent_messages):
|
||||
lines.append(f"- {message.role}: {message.content}")
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def build_llm_reply(db: Session, student_id: int, user_message: str) -> str:
|
||||
context = get_student_context(db, student_id)
|
||||
response = client.responses.create(
|
||||
model="gpt-4.1-mini",
|
||||
input=[
|
||||
{"role": "system", "content": SYSTEM_PROMPT},
|
||||
{
|
||||
"role": "user",
|
||||
"content": f"Contexte pédagogique:\n{context}\n\nMessage de l'élève:\n{user_message}",
|
||||
},
|
||||
],
|
||||
temperature=0.7,
|
||||
)
|
||||
return response.output_text.strip()
|
||||
|
||||
|
||||
def pick_next_skill(db: Session, student_id: int) -> models.Skill:
|
||||
weakest = (
|
||||
db.query(models.StudentSkillMastery)
|
||||
.filter_by(student_id=student_id)
|
||||
.order_by(models.StudentSkillMastery.mastery_score.asc())
|
||||
.first()
|
||||
)
|
||||
return db.query(models.Skill).filter_by(id=weakest.skill_id).first()
|
||||
|
||||
|
||||
def evaluate_answer(db: Session, student_id: int, skill_code: str, answer: str):
|
||||
q = QUESTIONS[skill_code]
|
||||
normalized_student = answer.strip().lower()
|
||||
normalized_expected = q["expected_answer"].strip().lower()
|
||||
correct = normalized_student == normalized_expected
|
||||
|
||||
skill = db.query(models.Skill).filter_by(code=skill_code).first()
|
||||
mastery = (
|
||||
db.query(models.StudentSkillMastery)
|
||||
.filter_by(student_id=student_id, skill_id=skill.id)
|
||||
.first()
|
||||
)
|
||||
|
||||
if correct:
|
||||
mastery.mastery_score = min(100.0, mastery.mastery_score + 8)
|
||||
mastery.confidence = min(1.0, mastery.confidence + 0.15)
|
||||
feedback = q["feedback_ok"]
|
||||
else:
|
||||
mastery.mastery_score = max(0.0, mastery.mastery_score - 6)
|
||||
mastery.confidence = min(1.0, mastery.confidence + 0.1)
|
||||
feedback = q["feedback_ko"]
|
||||
|
||||
mastery.evidence_count += 1
|
||||
|
||||
db.add(
|
||||
models.AssessmentAttempt(
|
||||
student_id=student_id,
|
||||
skill_code=skill_code,
|
||||
question=q["question"],
|
||||
expected_answer=q["expected_answer"],
|
||||
student_answer=answer,
|
||||
is_correct=1 if correct else 0,
|
||||
feedback=feedback,
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(mastery)
|
||||
return correct, feedback, mastery.mastery_score
|
||||
9
backend/requirements.txt
Normal file
9
backend/requirements.txt
Normal file
@@ -0,0 +1,9 @@
|
||||
fastapi==0.115.12
|
||||
uvicorn[standard]==0.34.0
|
||||
sqlalchemy==2.0.40
|
||||
psycopg2-binary==2.9.10
|
||||
pydantic==2.10.6
|
||||
python-dotenv==1.0.1
|
||||
openai==1.72.0
|
||||
redis==5.2.1
|
||||
alembic==1.15.2
|
||||
Reference in New Issue
Block a user