Something went wrong. Try again.
Synapse is a study workspace. Organize courses read and annotate the material, train with generated exercises and watch your progress forked from denishovart.com/synapse
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899import { BadRequestException, ForbiddenException, Inject, Injectable } from '@nestjs/common';import { randomUUID } from 'node:crypto';import { readFile } from 'node:fs/promises';import { Exercise, ExerciseType } from '../domain/models';import { AiSettingsService } from './ai-settings.service';import { BlobsService } from './blobs.service';import { DocumentsService } from './documents.service';import { DocumentRepository, ExerciseGeneratorPort } from '../domain/ports';import { DOCUMENT_REPOSITORY, EXERCISE_GENERATOR } from '../domain/ports';
const MIN_TEXT_FOR_GENERATION = 50;
// Generation is the one AI-heavy exercise concern left on the server: the// documents' extracted text lives here, and so does the configured provider// key. The rows are returned to the caller, never stored - the client's// workspace doc is the source of truth and syncs them to other devices.@Injectable()export class ExercisesService { constructor( @Inject(DOCUMENT_REPOSITORY) private readonly documents: DocumentRepository, @Inject(EXERCISE_GENERATOR) private readonly generator: ExerciseGeneratorPort, private readonly documentsService: DocumentsService, private readonly aiSettings: AiSettingsService, private readonly blobs: BlobsService, ) {}
async generate( input: { document_id?: string; count?: number; types?: ExerciseType[]; difficulty?: 'easy' | 'medium' | 'hard' | 'mixed'; course_id?: string; topic_id?: string; course_name?: string; topic_name?: string; promptTemplate?: string; text_hash?: string; }, ownerId: string | null, ): Promise<Exercise[]> { if (!input.document_id) throw new BadRequestException('document_id is required'); const documentId = input.document_id; await this.documentsService.assertOwner(documentId, ownerId); const doc = await this.documents.findById(documentId); let text = doc?.extracted_text ?? ''; // A document created on a device has no row here; its extracted text // arrives as a blob the device pushed, referenced by hash. if (text.trim().length < MIN_TEXT_FOR_GENERATION && input.text_hash) { text = (await this.textFromBlob(input.text_hash, ownerId)) ?? text; } if (!doc && !text) throw new BadRequestException('Document not found');
const ai = await this.aiSettings.get(); if (!ai.enabled) throw new ForbiddenException('AI features are disabled in settings'); if (text.trim().length < MIN_TEXT_FOR_GENERATION) { throw new BadRequestException( 'The text extracted from this document is too short or empty (scanned/image PDF with no text?)', ); }
const generated = await this.generator.generate({ courseName: input.course_name ?? '', topicName: input.topic_name || undefined, sourceText: text, count: input.count ?? 8, types: input.types ?? ['mcq', 'true_false', 'open'], difficulty: input.difficulty ?? 'mixed', promptTemplate: input.promptTemplate, ai, });
const now = new Date().toISOString().replace('T', ' ').slice(0, 19); return generated.map((item) => ({ id: randomUUID(), document_id: doc?.id ?? documentId, course_id: input.course_id ?? '', topic_id: input.topic_id ?? null, type: item.type, question: item.question, options: item.options && item.options.length ? JSON.stringify(item.options) : null, correct_answer: item.correct_answer, explanation: item.explanation || null, difficulty: item.difficulty || 'medium', source: 'ai', created_at: now, })); }
private async textFromBlob(hash: string, ownerId: string | null): Promise<string | null> { try { const { filepath } = await this.blobs.resolve(hash, ownerId); return await readFile(filepath, 'utf8'); } catch { return null; } }}