|
- import 'dart:convert';
- import 'package:http/http.dart' as http;
-
- /// Définit un contrat pour tout service capable de générer des idées de posts.
- abstract class PostCreationService {
- Future<List<String>> generatePostIdeas({
- required String base64Image,
- required String profession,
- required String tone,
- });
- }
-
- /// L'implémentation Ollama de ce service.
- class OllamaPostCreationService implements PostCreationService {
- final String _apiUrl = 'http://192.168.20.200:11434/api/generate';
- final String _visionModel = 'llava:7b';
-
- @override
- Future<List<String>> generatePostIdeas({
- required String base64Image,
- required String profession,
- required String tone,
- }) async {
- final requestPrompt = """
- You are a social media expert.
- Act as a "$profession".
- Analyze the image.
- Generate 3 short and engaging social media post ideas in french with a "$tone" tone.
- Your output MUST be a valid JSON array of strings.
-
- Example:
- ["", "", ""]
- """;
-
- final requestBody = {
- 'model': _visionModel,
- 'prompt': requestPrompt,
- 'images': [base64Image],
- 'stream': false,
- };
-
- try {
- print("[OllamaPostCreationService] 🚀 Appel pour générer des idées...");
- final response = await http.post(
- Uri.parse(_apiUrl),
- headers: {'Content-Type': 'application/json'},
- body: jsonEncode(requestBody),
- ).timeout(const Duration(minutes: 3));
-
- if (response.statusCode == 200) {
- final responseData = jsonDecode(response.body);
- final jsonString = (responseData['response'] as String? ?? '').trim();
-
- if (jsonString.isEmpty) return [];
-
- try {
- final ideasList = jsonDecode(jsonString) as List;
- return ideasList.map((idea) => idea.toString()).toList();
- } catch (e) {
- print("[OllamaPostCreationService] ❌ Erreur de parsing JSON. Réponse : $jsonString");
- return [jsonString]; // Retourne la réponse brute comme une seule idée
- }
- } else {
- throw Exception('Erreur Ollama (generatePostIdeas) ${response.statusCode}: ${response.body}');
- }
- } catch (e) {
- print("[OllamaPostCreationService] ❌ Exception : ${e.toString()}");
- rethrow;
- }
- }
- }
|