|
- import 'dart:convert';
- import 'package:http/http.dart' as http;
-
- // --- AJOUTS NÉCESSAIRES ---
- import '../domain/catalogs/filter_catalog.dart'; // 1. Importer le catalogue de filtres// --- MISE À JOUR DU CONTRAT (SIGNATURE DE LA MÉTHODE) ---
-
- /// L'objet retourné par l'analyse de l'IA
- typedef ImageAnalysisResult = ({String prompt, List<String> filterIds});
-
- /// Définit un contrat pour tout service capable d'analyser une image.
- abstract class ImageAnalysisService {
- /// Prend une image en base64 et retourne un prompt ET une liste d'ID de filtres.
- Future<ImageAnalysisResult> analyzeImage(String base64Image); // 2. Mettre à jour la signature
- }
-
- // --- MISE À JOUR DE L'IMPLÉMENTATION ---
-
- /// L'implémentation Ollama de ce service.
- class OllamaImageAnalysisService implements ImageAnalysisService {
- final String _apiUrl = 'http://192.168.20.200:11434/api/generate';
- final String _visionModel = 'llava:7b';
-
- @override
- Future<ImageAnalysisResult> analyzeImage(String base64Image) async {
- print("[OllamaImageAnalysisService] 🚀 Lancement de l'analyse et de la suggestion de filtres...");
-
- // 3. Préparer la liste des filtres pour l'IA
- final filterDescriptions = availableFilters.map((filter) {
- return "- ID: \"${filter.id}\"\n Description: ${filter.description}";
- }).join('\n\n');
-
- // 4. Mettre à jour le prompt système pour demander un JSON
- final requestPrompt = '''
- You are an expert image analyst and social media content director.
- Analyze the provided image and perform two tasks:
- 1. Generate a detailed, high-quality, descriptive prompt in English for an image generation model like Stable Diffusion. The prompt must focus on subject, style, lighting, and composition.
- 2. Choose the 3 BEST filters to enhance this image from the list below.
-
- Available filters:
- $filterDescriptions
-
- You MUST reply ONLY with a valid JSON object in the following format. Do not include any other text, markdown, or explanations.
- {
- "prompt": "your detailed image prompt here...",
- "filters": ["ID_OF_BEST_FILTER_1", "ID_OF_SECOND_BEST_FILTER_2", "ID_OF_THIRD_BEST_FILTER_3"]
- }
- ''';
-
- final requestBody = {
- 'model': _visionModel,
- 'prompt': requestPrompt,
- 'images': [base64Image],
- 'stream': false,
- // 5. Demander explicitement un retour en JSON
- 'format': 'json',
- };
-
- try {
- final response = await http.post(
- Uri.parse(_apiUrl),
- headers: {'Content-Type': 'application/json'},
- body: jsonEncode(requestBody),
- ).timeout(const Duration(minutes: 2));
-
- if (response.statusCode == 200) {
- // 6. Parser la réponse JSON
- final responseBodyString = jsonDecode(response.body)['response'] as String;
- final responseJson = jsonDecode(responseBodyString) as Map<String, dynamic>;
-
- final prompt = responseJson['prompt'] as String? ?? 'No prompt generated.';
- final filterIds = (responseJson['filters'] as List<dynamic>? ?? []).cast<String>();
-
- print('[OllamaImageAnalysisService] ✅ Analyse terminée. Prompt: $prompt, Filtres: $filterIds');
- return (prompt: prompt, filterIds: filterIds);
- } else {
- throw Exception('Erreur Ollama (analyzeImage) ${response.statusCode}: ${response.body}');
- }
- } catch (e) {
- print('[OllamaImageAnalysisService] ❌ Exception : ${e.toString()}');
- rethrow;
- }
- }
- }
|