Add React frontend and Sinbad2IA LLM integration.

Introduce a full Vite/React UI for exams, auth, materials, images, generation, and export.
Adapt backend for Sinbad2IA chat API, bcrypt passwords, CORS on port 5173, and schema migrations.
This commit is contained in:
Mireya Cueto Garrido
2026-06-01 13:27:41 +02:00
parent 7bc27da33a
commit 946f16a633
66 changed files with 6769 additions and 48 deletions
+10 -1
View File
@@ -6,7 +6,7 @@ from fastapi import APIRouter, Depends, status
from app.api.dependencies import get_exam_service, get_storage_quota_service
from app.core.auth import get_current_user
from app.models.user import User
from app.schemas.exam import ExamTemplateCreate, ExamTemplateRead
from app.schemas.exam import ExamTemplateCreate, ExamTemplateRead, QuestionRead
from app.schemas.storage import TemplateStorageUsage
from app.services.exam_service import ExamService
from app.services.storage_quota import StorageQuotaService
@@ -40,6 +40,15 @@ def get_template(
return service.get_template(current_user.id, template_id)
@router.get("/{template_id}/questions", response_model=list[QuestionRead])
def list_template_questions(
template_id: uuid.UUID,
current_user: Annotated[User, Depends(get_current_user)],
service: Annotated[ExamService, Depends(get_exam_service)],
) -> list[QuestionRead]:
return service.list_questions(current_user.id, template_id)
@router.get("/{template_id}/storage", response_model=TemplateStorageUsage)
def get_template_storage_usage(
template_id: uuid.UUID,
+4 -4
View File
@@ -10,14 +10,14 @@ class Settings(BaseSettings):
api_prefix: str = ""
api_key: str = Field(min_length=16)
database_url: str = "postgresql+psycopg://genexamenes:genexamenes@localhost:5432/genexamenes"
allowed_origins: str = "http://localhost:3000"
allowed_origins: str = "http://localhost:5173,http://localhost:3000"
rate_limit_requests: int = Field(default=60, ge=1)
rate_limit_window_seconds: int = Field(default=60, ge=1)
max_request_bytes: int = Field(default=1_048_576, ge=1_024)
llm_api_key: str | None = None
llm_base_url: str = "https://api.openai.com/v1"
llm_model: str = "gpt-4o-mini"
llm_timeout_seconds: int = Field(default=60, ge=5)
llm_base_url: str = ""
llm_model: str = "qwen3.5:35b"
llm_timeout_seconds: int = Field(default=180, ge=5)
jwt_secret_key: str = Field(min_length=32)
jwt_algorithm: str = "HS256"
jwt_expire_minutes: int = Field(default=60 * 24, ge=5)
+3
View File
@@ -17,6 +17,9 @@ class RateLimitMiddleware(BaseHTTPMiddleware):
self.requests: defaultdict[str, deque[float]] = defaultdict(deque)
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
if request.method == "OPTIONS":
return await call_next(request)
client = request.client.host if request.client else "unknown"
now = time.monotonic()
bucket = self.requests[client]
+2
View File
@@ -1,7 +1,9 @@
from app.db.base import Base
from app.db.migrations import run_migrations
from app.db.session import engine
from app.models import exam, user # noqa: F401
def init_db() -> None:
Base.metadata.create_all(bind=engine)
run_migrations(engine)
+104
View File
@@ -0,0 +1,104 @@
"""
Migraciones ligeras e idempotentes para bases de datos creadas antes de nuevas columnas.
Se ejecutan en cada arranque; solo aplican cambios que falten.
"""
from sqlalchemy import inspect, text
from sqlalchemy.engine import Engine
def run_migrations(engine: Engine) -> None:
inspector = inspect(engine)
table_names = set(inspector.get_table_names())
with engine.begin() as conn:
if "users" in table_names and "exam_templates" in table_names:
_ensure_exam_templates_user_id(conn, inspector)
if "questions" in table_names:
_ensure_questions_image_id(conn, inspector)
if "exam_materials" in table_names:
_ensure_material_status_enum(conn)
def _column_names(inspector, table: str) -> set[str]:
return {col["name"] for col in inspector.get_columns(table)}
def _ensure_exam_templates_user_id(conn, inspector) -> None:
if "user_id" in _column_names(inspector, "exam_templates"):
return
conn.execute(
text("ALTER TABLE exam_templates ADD COLUMN user_id UUID")
)
# Plantillas antiguas (sin usuario): asignar al primer usuario registrado.
conn.execute(
text(
"""
UPDATE exam_templates
SET user_id = (SELECT id FROM users ORDER BY created_at ASC LIMIT 1)
WHERE user_id IS NULL
AND EXISTS (SELECT 1 FROM users)
"""
)
)
# Si no hay usuarios o filas huérfanas, eliminar plantillas sin dueño.
conn.execute(text("DELETE FROM exam_templates WHERE user_id IS NULL"))
conn.execute(text("ALTER TABLE exam_templates ALTER COLUMN user_id SET NOT NULL"))
conn.execute(
text(
"""
ALTER TABLE exam_templates
ADD CONSTRAINT fk_exam_templates_user_id
FOREIGN KEY (user_id) REFERENCES users(id) ON DELETE CASCADE
"""
)
)
conn.execute(
text(
"CREATE INDEX IF NOT EXISTS ix_exam_templates_user_id ON exam_templates (user_id)"
)
)
def _ensure_questions_image_id(conn, inspector) -> None:
if "image_id" in _column_names(inspector, "questions"):
return
if "exam_images" not in set(inspector.get_table_names()):
return
conn.execute(text("ALTER TABLE questions ADD COLUMN image_id UUID"))
conn.execute(
text(
"""
ALTER TABLE questions
ADD CONSTRAINT fk_questions_image_id
FOREIGN KEY (image_id) REFERENCES exam_images(id) ON DELETE SET NULL
"""
)
)
conn.execute(
text("CREATE INDEX IF NOT EXISTS ix_questions_image_id ON questions (image_id)")
)
def _ensure_material_status_enum(conn) -> None:
# Asegura el tipo enum de PostgreSQL usado por exam_materials.status.
conn.execute(
text(
"""
DO $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM pg_type WHERE typname = 'materialstatus') THEN
CREATE TYPE materialstatus AS ENUM ('processed', 'failed');
END IF;
END
$$;
"""
)
)
+6 -3
View File
@@ -21,15 +21,18 @@ def create_app() -> FastAPI:
settings = get_settings()
app = FastAPI(title=settings.app_name, lifespan=lifespan)
# CORS debe ser el middleware más externo (añadirlo al final) para que
# las peticiones OPTIONS (preflight) respondan antes que rate limit, etc.
app.add_middleware(RequestSizeLimitMiddleware, settings=settings)
app.add_middleware(RateLimitMiddleware, settings=settings)
app.add_middleware(
CORSMiddleware,
allow_origins=settings.cors_origins,
allow_credentials=True,
allow_methods=["GET", "POST", "PATCH", "DELETE", "OPTIONS"],
allow_headers=["Authorization", "Content-Type", "X-API-Key"],
allow_headers=["Authorization", "Content-Type", "X-API-Key", "Accept"],
expose_headers=["Content-Disposition"],
)
app.add_middleware(RequestSizeLimitMiddleware, settings=settings)
app.add_middleware(RateLimitMiddleware, settings=settings)
register_exception_handlers(app)
+12 -4
View File
@@ -4,7 +4,7 @@ from typing import Annotated
from fastapi import Depends
from jose import JWTError, jwt
from passlib.context import CryptContext
import bcrypt
from sqlalchemy import select
from sqlalchemy.orm import Session
@@ -18,7 +18,15 @@ from app.db.session import get_db
from app.models.user import User
from app.schemas.user import UserLogin, UserRead, UserRegister
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")
def _hash_password(password: str) -> str:
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
def _verify_password(password: str, password_hash: str) -> bool:
try:
return bcrypt.checkpw(password.encode("utf-8"), password_hash.encode("utf-8"))
except ValueError:
return False
class AuthService:
@@ -34,7 +42,7 @@ class AuthService:
user = User(
email=email,
password_hash=pwd_context.hash(payload.password),
password_hash=_hash_password(payload.password),
full_name=clean_text(payload.full_name, max_length=200) if payload.full_name else None,
)
self.db.add(user)
@@ -47,7 +55,7 @@ class AuthService:
user = self.db.scalar(select(User).where(User.email == email))
if user is None or user.password_hash is None:
raise UnauthorizedError("Invalid email or password")
if not pwd_context.verify(payload.password, user.password_hash):
if not _verify_password(payload.password, user.password_hash):
raise UnauthorizedError("Invalid email or password")
return user
+5
View File
@@ -93,6 +93,11 @@ class ExamService:
def get_template(self, user_id: uuid.UUID, template_id: uuid.UUID) -> ExamTemplateRead:
return self._template_read(self._get_user_template_or_404(user_id, template_id))
def list_questions(self, user_id: uuid.UUID, template_id: uuid.UUID) -> list[QuestionRead]:
template = self._get_user_template_or_404(user_id, template_id)
questions = sorted(template.questions, key=lambda q: q.created_at)
return [self.to_question_read(question) for question in questions]
def get_owned_template(self, user_id: uuid.UUID, template_id: uuid.UUID) -> ExamTemplate:
return self._get_user_template_or_404(user_id, template_id)
+46 -21
View File
@@ -5,44 +5,69 @@ from app.core.errors import LLMUnavailableError
class LLMClient:
"""Cliente para el API de chat de Sinbad2IA (Ollama-compatible en UJA)."""
def __init__(self, settings: Settings) -> None:
self.settings = settings
async def generate(self, prompt: str) -> str:
if not self.settings.llm_api_key:
raise LLMUnavailableError("LLM_API_KEY is not configured")
def _chat_url(self) -> str:
base = self.settings.llm_base_url.rstrip("/")
if base.endswith("/api/chat"):
return base
return f"{base}/api/chat"
url = f"{self.settings.llm_base_url.rstrip('/')}/chat/completions"
async def generate(self, prompt: str) -> str:
payload = {
"model": self.settings.llm_model,
"messages": [
{
"role": "system",
"content": "You generate safe, valid JSON exam questions for Moodle imports.",
"role": "user",
"content": (
"Genera preguntas de examen en formato JSON válido para importar en Moodle. "
"Responde únicamente con el JSON solicitado, sin texto adicional ni bloques markdown.\n\n"
f"{prompt}"
),
},
{"role": "user", "content": prompt},
],
"temperature": 0.2,
"response_format": {"type": "json_object"},
}
headers = {
"Authorization": f"Bearer {self.settings.llm_api_key}",
"Content-Type": "application/json",
"stream": False,
}
headers = {"Content-Type": "application/json"}
if self.settings.llm_api_key:
headers["Authorization"] = f"Bearer {self.settings.llm_api_key}"
try:
async with httpx.AsyncClient(timeout=self.settings.llm_timeout_seconds) as client:
response = await client.post(url, json=payload, headers=headers)
response = await client.post(self._chat_url(), json=payload, headers=headers)
response.raise_for_status()
except httpx.HTTPError as exc:
raise LLMUnavailableError("LLM request failed") from exc
data = response.json()
try:
content = data["choices"][0]["message"]["content"]
except (KeyError, IndexError, TypeError) as exc:
raise LLMUnavailableError("LLM response did not include message content") from exc
if not isinstance(content, str) or not content.strip():
content = _extract_assistant_content(response.json())
if not content.strip():
raise LLMUnavailableError("LLM returned empty content")
return content
def _extract_assistant_content(data: object) -> str:
"""Soporta respuesta Sinbad2IA/Ollama (`message.content`) y OpenAI (`choices`)."""
if not isinstance(data, dict):
raise LLMUnavailableError("LLM response is not a JSON object")
message = data.get("message")
if isinstance(message, dict):
content = message.get("content")
if isinstance(content, str) and content.strip():
return content
choices = data.get("choices")
if isinstance(choices, list) and choices:
first = choices[0]
if isinstance(first, dict):
msg = first.get("message")
if isinstance(msg, dict):
content = msg.get("content")
if isinstance(content, str) and content.strip():
return content
raise LLMUnavailableError("LLM response did not include message content")