Compare commits
3 Commits
3d3747d3a2
...
main
| Author | SHA1 | Date | |
|---|---|---|---|
| 34d7ae8afc | |||
| 3533d3436b | |||
| 0b5bf8fba7 |
@@ -93,6 +93,20 @@ class _LoginPageState extends State<LoginPage> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Se role não existe na Firestore (null), permitir login e criar documento
|
||||
if (actualRole == null) {
|
||||
print(
|
||||
'DEBUG: Role não encontrado na Firestore, criando documento com role selecionado: $selectedRole',
|
||||
);
|
||||
try {
|
||||
await AuthService.createUserRole(uid, selectedRole);
|
||||
print('DEBUG: Role criado com sucesso');
|
||||
} catch (e) {
|
||||
print('DEBUG: Erro ao criar role: $e');
|
||||
// Continuar mesmo se falhar, pois o usuário já está autenticado
|
||||
}
|
||||
}
|
||||
|
||||
// Validar se o role selecionado corresponde ao role real
|
||||
if (actualRole != null && selectedRole != actualRole) {
|
||||
// Fazer logout imediato antes de mostrar erro
|
||||
@@ -118,6 +132,9 @@ class _LoginPageState extends State<LoginPage> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Usar selectedRole se actualRole for null (caso acabamos de criar)
|
||||
final finalRole = actualRole ?? selectedRole;
|
||||
|
||||
// Save session based on remember me preference
|
||||
await SessionService.saveSession(
|
||||
rememberMe: _rememberMe,
|
||||
@@ -137,7 +154,7 @@ class _LoginPageState extends State<LoginPage> {
|
||||
);
|
||||
|
||||
// Redirecionar baseado no role real
|
||||
if (actualRole == 'teacher') {
|
||||
if (finalRole == 'teacher') {
|
||||
context.go('/teacher-dashboard');
|
||||
} else {
|
||||
context.go('/student-dashboard');
|
||||
@@ -523,7 +540,9 @@ class _LoginPageState extends State<LoginPage> {
|
||||
// Signup link
|
||||
GestureDetector(
|
||||
onTap: () {
|
||||
context.go('/signup');
|
||||
context.go(
|
||||
'/signup?role=${widget.selectedRole}',
|
||||
);
|
||||
},
|
||||
child: Text(
|
||||
'Não tem conta? Criar aqui',
|
||||
|
||||
@@ -41,12 +41,14 @@ class _SignupPageState extends State<SignupPage> {
|
||||
Future<void> _loadAvailableClasses() async {
|
||||
setState(() => _isLoadingClasses = true);
|
||||
try {
|
||||
print('DEBUG: Loading school_classes from Firestore');
|
||||
final snapshot = await FirebaseFirestore.instance
|
||||
.collection('school_classes')
|
||||
.where('active', isEqualTo: true)
|
||||
.orderBy('year')
|
||||
.orderBy('section')
|
||||
.get();
|
||||
print('DEBUG: Loaded ${snapshot.docs.length} school classes');
|
||||
setState(() {
|
||||
_availableClasses = snapshot.docs.map((doc) {
|
||||
final data = doc.data();
|
||||
@@ -55,6 +57,7 @@ class _SignupPageState extends State<SignupPage> {
|
||||
_isLoadingClasses = false;
|
||||
});
|
||||
} catch (e) {
|
||||
print('DEBUG: Error loading school_classes: $e');
|
||||
setState(() => _isLoadingClasses = false);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'package:cloud_firestore/cloud_firestore.dart';
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_animate/flutter_animate.dart';
|
||||
import 'package:flutter/services.dart';
|
||||
import 'package:go_router/go_router.dart';
|
||||
import 'package:intl/intl.dart';
|
||||
import '../../../../core/services/auth_service.dart';
|
||||
import '../../../../core/theme/app_colors.dart';
|
||||
import '../../../../core/theme/app_theme_extension.dart';
|
||||
|
||||
/// Página para visualizar os alunos de uma turma específica
|
||||
@@ -202,9 +204,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
controller: textController,
|
||||
decoration: InputDecoration(
|
||||
labelText: 'Nome da Turma',
|
||||
border: OutlineInputBorder(
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
border: OutlineInputBorder(borderRadius: BorderRadius.circular(12)),
|
||||
prefixIcon: const Icon(Icons.school),
|
||||
),
|
||||
autofocus: true,
|
||||
@@ -254,10 +254,14 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
Container(
|
||||
padding: const EdgeInsets.all(12),
|
||||
decoration: BoxDecoration(
|
||||
color: Theme.of(context).colorScheme.error.withValues(alpha: 0.1),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.error.withValues(alpha: 0.1),
|
||||
borderRadius: BorderRadius.circular(8),
|
||||
border: Border.all(
|
||||
color: Theme.of(context).colorScheme.error.withValues(alpha: 0.3),
|
||||
color: Theme.of(
|
||||
context,
|
||||
).colorScheme.error.withValues(alpha: 0.3),
|
||||
),
|
||||
),
|
||||
child: Row(
|
||||
@@ -420,12 +424,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
|
||||
Widget _buildAppBar(ColorScheme cs) {
|
||||
return Container(
|
||||
padding: const EdgeInsets.only(
|
||||
left: 16,
|
||||
right: 16,
|
||||
top: 52,
|
||||
bottom: 16,
|
||||
),
|
||||
padding: const EdgeInsets.only(left: 16, right: 16, top: 52, bottom: 16),
|
||||
child: Column(
|
||||
children: [
|
||||
// Top Row with Back and Actions
|
||||
@@ -459,11 +458,20 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
// Delete Button
|
||||
Container(
|
||||
decoration: BoxDecoration(
|
||||
color: Colors.red.withValues(alpha: 0.2),
|
||||
color:
|
||||
(Theme.of(context).brightness == Brightness.dark
|
||||
? DarkBrandColors.primaryOrange
|
||||
: AppColors.primaryOrange)
|
||||
.withValues(alpha: 0.2),
|
||||
borderRadius: BorderRadius.circular(12),
|
||||
),
|
||||
child: IconButton(
|
||||
icon: const Icon(Icons.delete_outline, color: Colors.white),
|
||||
icon: Icon(
|
||||
Icons.delete_outline,
|
||||
color: Theme.of(context).brightness == Brightness.dark
|
||||
? DarkBrandColors.primaryOrange
|
||||
: AppColors.primaryOrange,
|
||||
),
|
||||
onPressed: _showDeleteClassDialog,
|
||||
tooltip: 'Eliminar turma',
|
||||
),
|
||||
@@ -626,7 +634,9 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
textAlign: TextAlign.center,
|
||||
),
|
||||
const SizedBox(height: 24),
|
||||
Container(
|
||||
GestureDetector(
|
||||
onTap: _copyCodeToClipboard,
|
||||
child: Container(
|
||||
padding: const EdgeInsets.symmetric(
|
||||
horizontal: 20,
|
||||
vertical: 12,
|
||||
@@ -654,12 +664,16 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
],
|
||||
),
|
||||
).animate().fadeIn(
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(
|
||||
duration: const Duration(milliseconds: 400),
|
||||
curve: Curves.easeOut,
|
||||
).then(delay: const Duration(milliseconds: 100)),
|
||||
)
|
||||
.then(delay: const Duration(milliseconds: 100)),
|
||||
],
|
||||
),
|
||||
);
|
||||
@@ -679,11 +693,7 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
margin: const EdgeInsets.only(bottom: 16, left: 8),
|
||||
child: Row(
|
||||
children: [
|
||||
Icon(
|
||||
Icons.people,
|
||||
color: cs.onSurface,
|
||||
size: 20,
|
||||
),
|
||||
Icon(Icons.people, color: cs.onSurface, size: 20),
|
||||
const SizedBox(width: 8),
|
||||
Text(
|
||||
'Alunos Matriculados',
|
||||
@@ -832,7 +842,11 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
borderRadius: BorderRadius.circular(10),
|
||||
),
|
||||
child: IconButton(
|
||||
icon: Icon(Icons.delete_outline, color: cs.error, size: 20),
|
||||
icon: Icon(
|
||||
Icons.delete_outline,
|
||||
color: cs.error,
|
||||
size: 20,
|
||||
),
|
||||
onPressed: () => _showRemoveStudentDialog(
|
||||
context,
|
||||
enrollmentId,
|
||||
@@ -848,16 +862,38 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
),
|
||||
),
|
||||
),
|
||||
).animate().fadeIn(
|
||||
)
|
||||
.animate()
|
||||
.fadeIn(
|
||||
duration: const Duration(milliseconds: 300),
|
||||
curve: Curves.easeOut,
|
||||
).then(delay: Duration(milliseconds: index * 50));
|
||||
)
|
||||
.then(delay: Duration(milliseconds: index * 50));
|
||||
}
|
||||
|
||||
String _formatDate(DateTime date) {
|
||||
return DateFormat('dd/MM/yyyy').format(date);
|
||||
}
|
||||
|
||||
void _copyCodeToClipboard() {
|
||||
Clipboard.setData(ClipboardData(text: _classCode ?? ''));
|
||||
ScaffoldMessenger.of(context).showSnackBar(
|
||||
SnackBar(
|
||||
content: Row(
|
||||
children: [
|
||||
const Icon(Icons.check_circle, color: Colors.white),
|
||||
const SizedBox(width: 12),
|
||||
const Text('Código copiado!'),
|
||||
],
|
||||
),
|
||||
backgroundColor: Colors.green,
|
||||
behavior: SnackBarBehavior.floating,
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
|
||||
duration: const Duration(seconds: 2),
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> _showRemoveStudentDialog(
|
||||
BuildContext context,
|
||||
String enrollmentId,
|
||||
@@ -869,7 +905,10 @@ class _ClassStudentsPageState extends State<ClassStudentsPage> {
|
||||
shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(16)),
|
||||
title: Row(
|
||||
children: [
|
||||
Icon(Icons.person_remove, color: Theme.of(context).colorScheme.error),
|
||||
Icon(
|
||||
Icons.person_remove,
|
||||
color: Theme.of(context).colorScheme.error,
|
||||
),
|
||||
const SizedBox(width: 8),
|
||||
const Text('Remover Aluno'),
|
||||
],
|
||||
|
||||
@@ -56,11 +56,6 @@ class _JoinClassPageState extends ConsumerState<JoinClassPage> {
|
||||
return;
|
||||
}
|
||||
|
||||
// Ler schoolClassId autorizado do aluno (definido no registo)
|
||||
final studentSchoolClassId = await AuthService.getStudentSchoolClassId(
|
||||
currentUser.uid,
|
||||
);
|
||||
|
||||
// Procurar disciplina pelo código
|
||||
final classQuery = await FirebaseFirestore.instance
|
||||
.collection('classes')
|
||||
@@ -76,20 +71,6 @@ class _JoinClassPageState extends ConsumerState<JoinClassPage> {
|
||||
|
||||
final classDoc = classQuery.docs.first;
|
||||
final classId = classDoc.id;
|
||||
final classSchoolClassId = classDoc.data()['schoolClassId'] as String?;
|
||||
|
||||
// Verificar se o aluno está autorizado a entrar nesta disciplina
|
||||
// O schoolClassId do aluno deve corresponder ao schoolClassId da disciplina
|
||||
if (studentSchoolClassId == null ||
|
||||
classSchoolClassId == null ||
|
||||
studentSchoolClassId != classSchoolClassId) {
|
||||
setState(() => _isLoading = false);
|
||||
_showError(
|
||||
'Não tens permissão para entrar nesta disciplina.\n'
|
||||
'O teu professor ainda não te adicionou a esta disciplina.',
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
// Verificar se já está inscrito nesta disciplina
|
||||
final existingEnrollment = await FirebaseFirestore.instance
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
import 'package:flutter/material.dart';
|
||||
|
||||
class TutorChatPage extends StatelessWidget {
|
||||
const TutorChatPage({super.key});
|
||||
|
||||
@override
|
||||
Widget build(BuildContext context) {
|
||||
return Scaffold(
|
||||
backgroundColor: Theme.of(context).colorScheme.background,
|
||||
appBar: AppBar(
|
||||
title: const Text('AI Tutor'),
|
||||
backgroundColor: Theme.of(context).colorScheme.surface,
|
||||
foregroundColor: Theme.of(context).colorScheme.onSurface,
|
||||
elevation: 0,
|
||||
),
|
||||
body: Container(
|
||||
decoration: BoxDecoration(
|
||||
gradient: LinearGradient(
|
||||
begin: Alignment.topLeft,
|
||||
end: Alignment.bottomRight,
|
||||
colors: [
|
||||
Theme.of(context).colorScheme.background,
|
||||
Theme.of(context).colorScheme.primary.withOpacity(0.1),
|
||||
Theme.of(context).colorScheme.secondary.withOpacity(0.05),
|
||||
Theme.of(context).colorScheme.background,
|
||||
],
|
||||
),
|
||||
),
|
||||
child: Center(
|
||||
child: Text(
|
||||
'AI Tutor Chat - Coming Soon',
|
||||
style: TextStyle(
|
||||
fontSize: 24,
|
||||
fontWeight: FontWeight.bold,
|
||||
color: Theme.of(context).colorScheme.onSurface,
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,224 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import '../lib/core/services/vector_service.dart';
|
||||
import '../lib/core/services/rag_service.dart';
|
||||
import '../lib/core/services/rag_ai_service.dart';
|
||||
import '../lib/core/models/content_chunk.dart';
|
||||
|
||||
void main() {
|
||||
group('AI Tutor RAG Services Tests', () {
|
||||
test('VectorService - Generate Embedding', () async {
|
||||
print('🔍 Testing VectorService embedding generation...');
|
||||
|
||||
const testText = 'A fotossíntese é o processo pelo qual as plantas convertem luz solar em energia química.';
|
||||
|
||||
final embedding = VectorService.generateEmbedding(testText);
|
||||
|
||||
// Verify embedding properties
|
||||
expect(embedding.length, equals(384)); // Standard embedding size
|
||||
expect(embedding.every((x) => x >= -1.0 && x <= 1.0), isTrue); // Normalized
|
||||
|
||||
print('✅ Embedding generated successfully: ${embedding.length} dimensions');
|
||||
});
|
||||
|
||||
test('VectorService - Cosine Similarity', () {
|
||||
print('🔍 Testing cosine similarity calculation...');
|
||||
|
||||
const text1 = 'A fotossíntese é importante para as plantas.';
|
||||
const text2 = 'As plantas usam fotossíntese para produzir energia.';
|
||||
const text3 = 'Os animais precisam de comida para sobreviver.';
|
||||
|
||||
final embedding1 = VectorService.generateEmbedding(text1);
|
||||
final embedding2 = VectorService.generateEmbedding(text2);
|
||||
final embedding3 = VectorService.generateEmbedding(text3);
|
||||
|
||||
final similarity12 = VectorService.cosineSimilarity(embedding1, embedding2);
|
||||
final similarity13 = VectorService.cosineSimilarity(embedding1, embedding3);
|
||||
|
||||
// Similar texts should have higher similarity
|
||||
expect(similarity12, greaterThan(similarity13));
|
||||
expect(similarity12, greaterThan(0.5)); // Should be reasonably similar
|
||||
expect(similarity13, lessThan(0.3)); // Should be less similar
|
||||
|
||||
print('✅ Cosine similarity working correctly');
|
||||
print(' Similar (fotossíntese): ${similarity12.toStringAsFixed(3)}');
|
||||
print(' Different (plantas vs animais): ${similarity13.toStringAsFixed(3)}');
|
||||
});
|
||||
|
||||
test('VectorService - Search by Text', () async {
|
||||
print('🔍 Testing vector search by text...');
|
||||
|
||||
// This would normally search the database, but we'll test the embedding part
|
||||
const query = 'O que é fotossíntese?';
|
||||
final results = await VectorService.searchByText(
|
||||
query: query,
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
grade: 10,
|
||||
k: 3,
|
||||
);
|
||||
|
||||
// Results might be empty if no data in database, but the call should work
|
||||
expect(results, isA<List<ContentChunk>>());
|
||||
|
||||
print('✅ Vector search completed');
|
||||
print(' Found ${results.length} results for: "$query"');
|
||||
});
|
||||
|
||||
test('RAGAIService - Service Availability', () async {
|
||||
print('🔍 Testing Ollama service availability...');
|
||||
|
||||
try {
|
||||
final isAvailable = await RAGAIService.isServiceAvailable();
|
||||
|
||||
if (isAvailable) {
|
||||
print('✅ Ollama service is available');
|
||||
|
||||
// Test model info
|
||||
final modelInfo = await RAGAIService.getModelInfo();
|
||||
if (modelInfo != null) {
|
||||
print(' Model: ${modelInfo['name']}');
|
||||
print(' Size: ${modelInfo['size']}');
|
||||
print(' Modified: ${modelInfo['modified']}');
|
||||
}
|
||||
|
||||
// Test simple query
|
||||
final testResponse = await RAGAIService.testService();
|
||||
print(' Test response: "$testResponse"');
|
||||
} else {
|
||||
print('⚠️ Ollama service is not available');
|
||||
print(' This is expected if the service is not running');
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ Error testing service availability: $e');
|
||||
}
|
||||
});
|
||||
|
||||
test('RAG Pipeline - End-to-End Simulation', () async {
|
||||
print('🔍 Testing complete RAG pipeline simulation...');
|
||||
|
||||
try {
|
||||
const userQuery = 'O que é fotossíntese?';
|
||||
const mode = TutorMode.explanation;
|
||||
|
||||
// Step 1: Test query embedding
|
||||
final queryEmbedding = VectorService.generateEmbedding(userQuery);
|
||||
print(' ✅ Query embedding generated (${queryEmbedding.length} dims)');
|
||||
|
||||
// Step 2: Test vector search
|
||||
final searchResults = await VectorService.searchSimilar(
|
||||
queryEmbedding: queryEmbedding,
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
grade: 10,
|
||||
k: 3,
|
||||
);
|
||||
print(' ✅ Vector search completed (${searchResults.length} results)');
|
||||
|
||||
// Step 3: Test RAG processing (with mock data if no real data)
|
||||
if (searchResults.isEmpty) {
|
||||
print(' ⚠️ No content found, creating mock data for testing...');
|
||||
|
||||
// Create mock chunks for testing
|
||||
final mockChunks = [
|
||||
ContentChunk(
|
||||
id: 'mock1',
|
||||
contentId: 'mock_content1',
|
||||
text: 'A fotossíntese é o processo pelo qual as plantas convertem luz solar em energia química.',
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
unit: 'Processos Biológicos',
|
||||
difficulty: 0.6,
|
||||
grade: 10,
|
||||
embedding: VectorService.generateEmbedding('fotossíntese plantas energia'),
|
||||
sourceDocument: 'Biologia Manual.pdf',
|
||||
metadata: {'page': 45},
|
||||
createdAt: DateTime.now(),
|
||||
),
|
||||
];
|
||||
|
||||
// Test RAG processing with mock data
|
||||
final ragResponse = await RAGService.processQuery(
|
||||
userQuery: userQuery,
|
||||
mode: mode,
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
grade: 10,
|
||||
maxSources: 3,
|
||||
);
|
||||
|
||||
print(' ✅ RAG processing completed');
|
||||
print(' Answer: "${ragResponse.answer.substring(0, 100)}..."');
|
||||
print(' Confidence: ${ragResponse.confidence.toStringAsFixed(2)}');
|
||||
print(' Sources: ${ragResponse.sources.length}');
|
||||
print(' Related concepts: ${ragResponse.relatedConcepts.join(', ')}');
|
||||
|
||||
} else {
|
||||
print(' ✅ Found real content for RAG processing');
|
||||
|
||||
// Test with real data
|
||||
final ragResponse = await RAGService.processQuery(
|
||||
userQuery: userQuery,
|
||||
mode: mode,
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
grade: 10,
|
||||
maxSources: 3,
|
||||
);
|
||||
|
||||
print(' ✅ RAG processing with real data completed');
|
||||
print(' Answer: "${ragResponse.answer.substring(0, 100)}..."');
|
||||
print(' Confidence: ${ragResponse.confidence.toStringAsFixed(2)}');
|
||||
print(' Sources: ${ragResponse.sources.length}');
|
||||
}
|
||||
|
||||
print('✅ RAG pipeline simulation completed successfully');
|
||||
|
||||
} catch (e) {
|
||||
print('❌ Error in RAG pipeline: $e');
|
||||
}
|
||||
});
|
||||
|
||||
test('VectorService - Batch Embeddings', () async {
|
||||
print('🔍 Testing batch embedding generation...');
|
||||
|
||||
final texts = [
|
||||
'A fotossíntese converte luz solar em energia.',
|
||||
'As plantas usam clorofila para capturar luz.',
|
||||
'O oxigénio é um subproduto da fotossíntese.',
|
||||
];
|
||||
|
||||
final embeddings = await VectorService.batchGenerateEmbeddings(texts);
|
||||
|
||||
expect(embeddings.length, equals(texts.length));
|
||||
expect(embeddings.every((e) => e.length == 384), isTrue);
|
||||
|
||||
print('✅ Batch embeddings generated successfully');
|
||||
print(' Generated ${embeddings.length} embeddings');
|
||||
|
||||
// Test similarities between batch embeddings
|
||||
for (int i = 0; i < embeddings.length; i++) {
|
||||
for (int j = i + 1; j < embeddings.length; j++) {
|
||||
final similarity = VectorService.cosineSimilarity(embeddings[i], embeddings[j]);
|
||||
print(' Similarity ${i+1}-${j+1}: ${similarity.toStringAsFixed(3)}');
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('VectorService - Statistics', () async {
|
||||
print('🔍 Testing vector statistics...');
|
||||
|
||||
final stats = await VectorService.getVectorStats();
|
||||
|
||||
expect(stats, isA<Map<String, dynamic>>());
|
||||
expect(stats.containsKey('totalChunks'), isTrue);
|
||||
expect(stats.containsKey('embeddingDimension'), isTrue);
|
||||
expect(stats['embeddingDimension'], equals(384));
|
||||
|
||||
print('✅ Vector statistics retrieved');
|
||||
print(' Total chunks: ${stats['totalChunks']}');
|
||||
print(' Embedding dimension: ${stats['embeddingDimension']}');
|
||||
print(' Subjects: ${stats['subjects'].keys.length}');
|
||||
print(' Concepts: ${stats['concepts'].keys.length}');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,154 +0,0 @@
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import '../lib/core/services/vector_service.dart';
|
||||
import '../lib/core/services/rag_ai_service.dart';
|
||||
import '../lib/core/services/rag_service.dart' show TutorMode;
|
||||
import '../lib/core/models/content_chunk.dart';
|
||||
|
||||
void main() {
|
||||
group('AI Tutor RAG Services Tests', () {
|
||||
setUpAll(() async {
|
||||
// Setup test data
|
||||
print('🧪 Setting up test environment...');
|
||||
});
|
||||
|
||||
test('VectorService - Generate Embedding', () async {
|
||||
print('🔍 Testing VectorService embedding generation...');
|
||||
|
||||
const testText =
|
||||
'A fotossíntese é o processo pelo qual as plantas convertem luz solar em energia química.';
|
||||
|
||||
final embedding = VectorService.generateEmbedding(testText);
|
||||
|
||||
// Verify embedding properties
|
||||
expect(embedding.length, equals(384)); // Standard embedding size
|
||||
expect(
|
||||
embedding.every((x) => x >= -1.0 && x <= 1.0),
|
||||
isTrue,
|
||||
); // Normalized
|
||||
|
||||
print(
|
||||
'✅ Embedding generated successfully: ${embedding.length} dimensions',
|
||||
);
|
||||
});
|
||||
|
||||
test('VectorService - Cosine Similarity', () {
|
||||
print('🔍 Testing cosine similarity calculation...');
|
||||
|
||||
const text1 = 'A fotossíntese é importante para as plantas.';
|
||||
const text2 = 'As plantas usam fotossíntese para produzir energia.';
|
||||
const text3 = 'Os animais precisam de comida para sobreviver.';
|
||||
|
||||
final embedding1 = VectorService.generateEmbedding(text1);
|
||||
final embedding2 = VectorService.generateEmbedding(text2);
|
||||
final embedding3 = VectorService.generateEmbedding(text3);
|
||||
|
||||
final similarity12 = VectorService.cosineSimilarity(
|
||||
embedding1,
|
||||
embedding2,
|
||||
);
|
||||
final similarity13 = VectorService.cosineSimilarity(
|
||||
embedding1,
|
||||
embedding3,
|
||||
);
|
||||
|
||||
// Similar texts should have higher similarity
|
||||
expect(similarity12, greaterThan(similarity13));
|
||||
expect(similarity12, greaterThan(0.5)); // Should be reasonably similar
|
||||
expect(similarity13, lessThan(0.3)); // Should be less similar
|
||||
|
||||
print('✅ Cosine similarity working correctly');
|
||||
print(' Similar (fotossíntese): ${similarity12.toStringAsFixed(3)}');
|
||||
print(
|
||||
' Different (plantas vs animais): ${similarity13.toStringAsFixed(3)}',
|
||||
);
|
||||
});
|
||||
|
||||
test('RAGAIService - Service Availability', () async {
|
||||
print('🔍 Testing Ollama service availability...');
|
||||
|
||||
try {
|
||||
final isAvailable = await RAGAIService.isServiceAvailable();
|
||||
|
||||
if (isAvailable) {
|
||||
print('✅ Ollama service is available');
|
||||
|
||||
// Test model info
|
||||
final modelInfo = await RAGAIService.getModelInfo();
|
||||
if (modelInfo != null) {
|
||||
print(' Model: ${modelInfo['name']}');
|
||||
print(' Size: ${modelInfo['size']}');
|
||||
print(' Modified: ${modelInfo['modified']}');
|
||||
}
|
||||
|
||||
// Test simple query
|
||||
final testResponse = await RAGAIService.testService();
|
||||
print(' Test response: "$testResponse"');
|
||||
} else {
|
||||
print('⚠️ Ollama service is not available');
|
||||
print(' This is expected if the service is not running');
|
||||
}
|
||||
} catch (e) {
|
||||
print('❌ Error testing service availability: $e');
|
||||
}
|
||||
});
|
||||
|
||||
test('RAG Pipeline - End-to-End Simulation', () async {
|
||||
print('🔍 Testing complete RAG pipeline simulation...');
|
||||
|
||||
try {
|
||||
const userQuery = 'O que é fotossíntese?';
|
||||
const mode = TutorMode.explanation;
|
||||
|
||||
// Step 1: Generate query embedding
|
||||
final queryEmbedding = VectorService.generateEmbedding(userQuery);
|
||||
print(' ✅ Query embedding generated');
|
||||
|
||||
// Step 2: Simulate content retrieval (mock data)
|
||||
final mockChunks = [
|
||||
ContentChunk(
|
||||
id: 'chunk1',
|
||||
contentId: 'content1',
|
||||
text:
|
||||
'A fotossíntese é o processo pelo qual as plantas, algas e algumas bactérias convertem luz solar em energia química.',
|
||||
subject: 'Biologia',
|
||||
concept: 'Fotossíntese',
|
||||
unit: 'Processos Biológicos',
|
||||
difficulty: 0.6,
|
||||
grade: 10,
|
||||
embedding: VectorService.generateEmbedding(
|
||||
'fotossíntese plantas energia',
|
||||
),
|
||||
sourceDocument: 'Biologia Manual.pdf',
|
||||
metadata: {'page': 45},
|
||||
createdAt: DateTime.now(),
|
||||
),
|
||||
];
|
||||
|
||||
// Step 3: Test AI service if available
|
||||
try {
|
||||
final ragResponse = await RAGAIService.generateRAGResponse(
|
||||
userQuery: userQuery,
|
||||
context: userQuery,
|
||||
mode: mode,
|
||||
sources: mockChunks,
|
||||
);
|
||||
|
||||
print(' ✅ RAG response generated');
|
||||
print(' Answer: "${ragResponse.answer.substring(0, 100)}..."');
|
||||
print(' Confidence: ${ragResponse.confidence.toStringAsFixed(2)}');
|
||||
print(' Sources: ${ragResponse.sources.length}');
|
||||
} catch (e) {
|
||||
print(' ⚠️ AI service not available: $e');
|
||||
}
|
||||
|
||||
print('✅ RAG pipeline simulation completed successfully');
|
||||
} catch (e) {
|
||||
print('❌ Error in RAG pipeline: $e');
|
||||
}
|
||||
});
|
||||
|
||||
tearDownAll(() async {
|
||||
print('🧹 Cleaning up test environment...');
|
||||
});
|
||||
});
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
// This is a basic Flutter widget test.
|
||||
//
|
||||
// To perform an interaction with a widget in your test, use the WidgetTester
|
||||
// utility in the flutter_test package. For example, you can send tap and scroll
|
||||
// gestures. You can also use WidgetTester to find child widgets in the widget
|
||||
// tree, read text, and verify that the values of widget properties are correct.
|
||||
|
||||
import 'package:flutter/material.dart';
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:learn_it/main.dart';
|
||||
|
||||
void main() {
|
||||
testWidgets('Counter increments smoke test', (WidgetTester tester) async {
|
||||
// Build our app and trigger a frame.
|
||||
await tester.pumpWidget(const MyApp());
|
||||
|
||||
// Verify that our counter starts at 0.
|
||||
expect(find.text('0'), findsOneWidget);
|
||||
expect(find.text('1'), findsNothing);
|
||||
|
||||
// Tap the '+' icon and trigger a frame.
|
||||
await tester.tap(find.byIcon(Icons.add));
|
||||
await tester.pump();
|
||||
|
||||
// Verify that our counter has incremented.
|
||||
expect(find.text('0'), findsNothing);
|
||||
expect(find.text('1'), findsOneWidget);
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user