feat: unified 1..9 words session narrative, dice input before reveal, dedicated results screen, and clean session history grouping

This commit is contained in:
Alma Alexyz
2026-08-31 15:23:59 +05:00
parent bc892c3388
commit 6f9d4d4cca
11 changed files with 1207 additions and 1099 deletions
+134 -150
View File
@@ -1,6 +1,7 @@
import 'dart:async';
import 'dart:convert';
import 'dart:math';
import 'package:http/http.dart' as http;
import '../models/history_entry_model.dart';
import '../models/word_model.dart';
class AiOracleService {
@@ -8,181 +9,164 @@ class AiOracleService {
factory AiOracleService() => _instance;
AiOracleService._internal();
// Configurable local or remote G4F server URL
String g4fServerUrl = 'http://localhost:1337/v1/chat/completions';
/// Interprets a full multi-word session narrative (1 to 9 words)
Future<String> interpretSession({
required List<SessionWord> words,
required String question,
}) async {
if (words.isEmpty) return 'Нет знаков для трактовки.';
/// Generates an esoteric, archetypal interpretation weaving the user's question, the drawn word, its session number, and its symbolic meaning.
final wordsNarrative = StringBuffer();
for (int i = 0; i < words.length; i++) {
final w = words[i];
final pos = w.positionTitle != null ? ' (${w.positionTitle})' : '';
wordsNarrative.writeln('${i + 1}. Знак #${w.formattedSessionNumber} «${w.word.toUpperCase()}»$pos — ${w.partOfSpeech}.');
wordsNarrative.writeln(' Смысл: ${w.symbolicMeaning}');
}
final prompt = _buildMultiWordPrompt(
question: question,
wordsNarrative: wordsNarrative.toString(),
wordsCount: words.length,
);
// 1. Try Pollinations OpenAI-compatible gateway (GPT-4o-mini / Llama 3.3 free tier)
try {
final res = await _callPollinationsOpenAi(prompt);
if (res != null && res.trim().isNotEmpty) return res.trim();
} catch (_) {}
// 2. Try Direct Pollinations Raw Gateway
try {
final res = await _callPollinationsDirect(prompt);
if (res != null && res.trim().isNotEmpty) return res.trim();
} catch (_) {}
// 3. Try Local G4F Server if running
try {
final res = await _callLocalG4f(prompt);
if (res != null && res.trim().isNotEmpty) return res.trim();
} catch (_) {}
// 4. Offline Multi-Word Synthesizer
return _generateOfflineSessionInterpretation(words, question);
}
/// Single word legacy interpretation helper
Future<String> interpret({
required WordItem word,
required String question,
String? spreadType,
String? positionTitle,
}) async {
final cleanQuestion = question.trim().isEmpty ? 'Общий совет и скрытые тенденции момента' : question.trim();
final systemPrompt =
'Ты — мудрый и глубокий Оракул 999 Сакральных Символов. '
'Твоя задача — связать выпавший сакральный знак, его номер и архетипический смысл с конкретным вопросом вопрошающего. '
'Дай глубокий, связный, образный и практичный ответ на русском языке. '
'Структурируй толкование: '
'1) Суть послания через призму вопроса. '
'2) Скрытый вызов / предупреждение. '
'3) Практический духовный совет / ключ к действию. '
'Пиши емко, выразительно, без лишней «воды», на 2-4 абзаца.';
final userPrompt =
'Вопрос вопрошающего: «$cleanQuestion»\n'
'Выпавший знак: #${word.formattedSessionNumber} — «${word.word.toUpperCase()}» (${word.partOfSpeech})\n'
'${positionTitle != null ? "Позиция в раскладе: $positionTitle\n" : ""}'
'Базовое символическое значение знака: ${word.description}\n\n'
'Сотки глубокую трактовку этого знака именно для заданного вопроса.';
// Try Provider 1: Local / Configured G4F Server
try {
final g4fResponse = await _callOpenAiCompatible(
url: g4fServerUrl,
systemPrompt: systemPrompt,
userPrompt: userPrompt,
timeout: const Duration(seconds: 4),
);
if (g4fResponse != null && g4fResponse.isNotEmpty) {
return g4fResponse;
}
} catch (_) {}
// Try Provider 2: Pollinations AI OpenAI-compatible Gateway (Free GPT-4o-mini tier)
try {
final pollResponse = await _callOpenAiCompatible(
url: 'https://text.pollinations.ai/openai/chat/completions',
systemPrompt: systemPrompt,
userPrompt: userPrompt,
timeout: const Duration(seconds: 10),
);
if (pollResponse != null && pollResponse.isNotEmpty) {
return pollResponse;
}
} catch (_) {}
// Try Provider 3: Pollinations AI Raw Text Gateway (GET / POST)
try {
final rawResponse = await _callPollinationsRaw(
systemPrompt: systemPrompt,
userPrompt: userPrompt,
timeout: const Duration(seconds: 8),
);
if (rawResponse != null && rawResponse.isNotEmpty) {
return rawResponse;
}
} catch (_) {}
// Provider 4 (Fallback): Offline Sacred Synthesis Engine
return _generateOfflineInterpretation(
word: word,
question: cleanQuestion,
positionTitle: positionTitle,
);
final sessionWord = SessionWord.fromWordItem(word, positionTitle: positionTitle);
return interpretSession(words: [sessionWord], question: question);
}
/// Helper for OpenAI / G4F compatible JSON completions
Future<String?> _callOpenAiCompatible({
required String url,
required String systemPrompt,
required String userPrompt,
required Duration timeout,
}) async {
final response = await http
String _buildMultiWordPrompt({
required String question,
required String wordsNarrative,
required int wordsCount,
}) {
final userQuestion = question.trim().isNotEmpty
? 'Вопрос вопрошающего: «$question»'
: 'Вопрос не задан вслух (общий вектор судьбы и текущий момент).';
return '''Ты — Священный Оракул Клеромантии 999. Твоя задача — дать глубокое, психологически тонкое, символически связное толкование выпавших знаков жребия.
$userQuestion
Выпавшие знаки жребия ($wordsCount слов в единой цепочке):
$wordsNarrative
Требования к ответу:
1. Свяжи все выпавшие знаки в единую осмысленную историю-путь, прямо отвечающую на вопрос.
2. Раскрой скрытый символический конфликт или вектор развития ситуации.
3. Дай конкретный совет и практический духовный ориентир.
4. Ответ напиши на русском языке, поэтично, ёмко и лаконично (3-5 предложений), без лишней воды.''';
}
Future<String?> _callPollinationsOpenAi(String prompt) async {
final url = Uri.parse('https://text.pollinations.ai/openai/chat/completions');
final body = jsonEncode({
'model': 'openai',
'messages': [
{'role': 'system', 'content': 'Ты — глубокий символический оракул и толкователь священного жребия.'},
{'role': 'user', 'content': prompt},
],
'temperature': 0.7,
});
final resp = await http
.post(
Uri.parse(url),
url,
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json',
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
},
body: jsonEncode({
'model': 'gpt-4o-mini',
'messages': [
{'role': 'system', 'content': systemPrompt},
{'role': 'user', 'content': userPrompt},
],
'temperature': 0.7,
'max_tokens': 700,
}),
body: body,
)
.timeout(timeout);
.timeout(const Duration(seconds: 10));
if (response.statusCode >= 200 && response.statusCode < 300) {
final data = jsonDecode(utf8.decode(response.bodyBytes));
if (data is Map && data.containsKey('choices')) {
final choices = data['choices'] as List;
if (choices.isNotEmpty) {
final first = choices.first;
if (first is Map && first.containsKey('message')) {
final content = first['message']['content'] as String?;
if (content != null && content.trim().isNotEmpty) {
return content.trim();
}
}
}
}
if (resp.statusCode == 200) {
final data = jsonDecode(utf8.decode(resp.bodyBytes));
return data['choices']?[0]?['message']?['content'] as String?;
}
return null;
}
/// Helper for Pollinations Raw text generation
Future<String?> _callPollinationsRaw({
required String systemPrompt,
required String userPrompt,
required Duration timeout,
}) async {
final combined = '$systemPrompt\n\n$userPrompt';
final uri = Uri.parse('https://text.pollinations.ai/').replace(
queryParameters: {
'model': 'openai',
'json': 'false',
'seed': DateTime.now().millisecondsSinceEpoch.toString(),
Future<String?> _callPollinationsDirect(String prompt) async {
final encodedPrompt = Uri.encodeComponent(prompt);
final seed = Random().nextInt(1000000);
final url = Uri.parse('https://text.pollinations.ai/$encodedPrompt?seed=$seed&model=openai');
final resp = await http.get(
url,
headers: {
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)',
},
);
).timeout(const Duration(seconds: 10));
final response = await http
.post(
uri,
headers: {
'Content-Type': 'text/plain; charset=utf-8',
'User-Agent': 'Mozilla/5.0 (X11; Linux x86_64)',
},
body: utf8.encode(combined),
)
.timeout(timeout);
if (response.statusCode >= 200 && response.statusCode < 300) {
final text = utf8.decode(response.bodyBytes).trim();
if (text.isNotEmpty && !text.startsWith('Error')) {
if (resp.statusCode == 200) {
final text = utf8.decode(resp.bodyBytes).trim();
if (text.isNotEmpty && !text.startsWith('<!DOCTYPE html')) {
return text;
}
}
return null;
}
/// Offline fallback generator in case of network unavailability
String _generateOfflineInterpretation({
required WordItem word,
required String question,
String? positionTitle,
}) {
final pos = word.partOfSpeech.toLowerCase();
String focus = 'ключевую сферу кристаллизации';
if (pos.contains('глагол')) {
focus = 'необходимый вектор действия и трансформации';
} else if (pos.contains('прилаг')) {
focus = 'вибрационное качество и внутреннее состояние';
} else if (pos.contains('нареч')) {
focus = 'модус и темп развертывания судьбы';
}
Future<String?> _callLocalG4f(String prompt) async {
final url = Uri.parse('http://localhost:1337/v1/chat/completions');
final body = jsonEncode({
'model': 'gpt-4o-mini',
'messages': [
{'role': 'user', 'content': prompt},
],
});
return '🔮 Послание знака #${word.formattedSessionNumber} «${word.word.toUpperCase()}» на ваш запрос «$question»:\n\n'
'1. Смысловой узел: Символ указывает на $focus в текущей ситуации. ${word.description}\n\n'
'2. Внутренний вызов: Обратите внимание на то, как энергия слова «${word.word}» соотносится с вашими скрытыми ожиданиями. '
'Не пытайтесь форсировать события вопреки естественному ритму.\n\n'
'3. Ключ к действию: Примите качества этого знака как ориентир для принятия решения в ближайшие дни.';
final resp = await http
.post(
url,
headers: {'Content-Type': 'application/json'},
body: body,
)
.timeout(const Duration(seconds: 5));
if (resp.statusCode == 200) {
final data = jsonDecode(utf8.decode(resp.bodyBytes));
return data['choices']?[0]?['message']?['content'] as String?;
}
return null;
}
String _generateOfflineSessionInterpretation(List<SessionWord> words, String question) {
final wordsListStr = words.map((w) => '«${w.word.toUpperCase()}» (#${w.formattedSessionNumber})').join(' ➔ ');
final questionContext = question.trim().isNotEmpty
? 'В контексте вашего вопроса «$question» '
: 'В пространстве текущего момента ';
return '$questionContext выпавшая связка знаков ($wordsListStr) указывает на непрерывную динамику перехода. '
'Первый знак («${words.first.word}») задает скрытый импульс и причину, а завершающий знак («${words.last.word}») указывает на ключ к гармоничному исходу. '
'Синтез значений призывает осознать взаимосвязь противоположностей и сделать шаг навстречу созиданию.';
}
}
+80 -88
View File
@@ -1,4 +1,3 @@
import 'dart:convert';
import 'dart:math';
import 'package:shared_preferences/shared_preferences.dart';
import '../data/words_data.dart';
@@ -10,111 +9,76 @@ class WordsRepository {
factory WordsRepository() => _instance;
WordsRepository._internal();
final List<WordItem> _masterWords = List.from(kRussianTop1000Words);
static const String _kHistoryKey = 'oracle_999_sessions_history_v2';
List<WordItem> _sessionWords = [];
final List<HistoryEntry> _history = [];
bool _isInitialized = false;
final List<OracleSession> _sessions = [];
List<WordItem> get allWords => List.unmodifiable(_sessionWords);
List<OracleSession> get sessions => List.unmodifiable(_sessions);
List<OracleSession> get history => sessions; // Alias for compatibility
int get totalWords => _sessionWords.length;
List<HistoryEntry> get history => List.unmodifiable(_history);
Future<void> init() async {
if (_isInitialized) return;
// Always reshuffle session numbers on startup for true synchronicity & randomization
reshuffleSessionNumbers();
// 1. Initialize random session mapping
_initializeSessionMapping();
// Load history from persistence
try {
final prefs = await SharedPreferences.getInstance();
final historyJsonList = prefs.getStringList('oracle_history_entries') ?? [];
_history.clear();
for (final str in historyJsonList) {
try {
final map = jsonDecode(str) as Map<String, dynamic>;
_history.add(HistoryEntry.fromMap(map));
} catch (_) {}
}
} catch (_) {}
_isInitialized = true;
// 2. Load stored session history
await _loadHistoryFromPrefs();
}
/// Cryptographic/pseudo-random Fisher-Yates shuffle to map 000..999 to words for the current session
void reshuffleSessionNumbers() {
void _initializeSessionMapping() {
final list = List<WordItem>.from(kRussianTop1000Words);
final random = Random();
final indices = List<int>.generate(_masterWords.length, (i) => i);
indices.shuffle(random);
final mappedList = <WordItem>[];
for (int i = 0; i < _masterWords.length; i++) {
final baseWord = _masterWords[indices[i]];
// i is the dynamic sessionNumber (0..999)
final sessionItem = baseWord.copyWith(sessionNumber: i);
mappedList.add(sessionItem);
// Fisher-Yates shuffle
for (int i = list.length - 1; i > 0; i--) {
int n = random.nextInt(i + 1);
final temp = list[i];
list[i] = list[n];
list[n] = temp;
}
_sessionWords = mappedList;
_sessionWords = [];
for (int i = 0; i < list.length; i++) {
_sessionWords.add(list[i].copyWith(sessionNumber: i));
}
}
WordItem? getWordBySessionNumber(int sessionNum) {
if (sessionNum < 0 || sessionNum >= _sessionWords.length) return null;
return _sessionWords[sessionNum];
void reshuffleSessionNumbers() {
_initializeSessionMapping();
}
WordItem? getWordById(int id) {
return getWordBySessionNumber(id);
WordItem? getWordBySessionNumber(int number) {
if (number < 0 || number >= _sessionWords.length) return null;
return _sessionWords[number];
}
WordItem getRandomWord() {
if (_sessionWords.isEmpty) {
return _masterWords.first;
}
final random = Random();
final index = random.nextInt(_sessionWords.length);
return _sessionWords[index];
final idx = random.nextInt(_sessionWords.length);
return _sessionWords[idx];
}
WordItem getNextWord(int currentSessionNum) {
if (_sessionWords.isEmpty) return getRandomWord();
final nextId = (currentSessionNum + 1) % _sessionWords.length;
return _sessionWords[nextId];
WordItem getNextWord(int currentSessionNumber) {
int nextNumber = (currentSessionNumber + 1) % _sessionWords.length;
return _sessionWords[nextNumber];
}
WordItem getPreviousWord(int currentSessionNum) {
if (_sessionWords.isEmpty) return getRandomWord();
final prevId = (currentSessionNum - 1 + _sessionWords.length) % _sessionWords.length;
return _sessionWords[prevId];
WordItem getPreviousWord(int currentSessionNumber) {
int prevNumber = (currentSessionNumber - 1 + _sessionWords.length) % _sessionWords.length;
return _sessionWords[prevNumber];
}
List<WordItem> search(String rawQuery) {
final query = rawQuery.trim().toLowerCase();
if (query.isEmpty) return _sessionWords;
List<WordItem> search(String query) {
query = query.trim().toLowerCase();
if (query.isEmpty) return [];
// Check if query is a number (e.g. 0, 00, 000, 42, 042, 999)
final number = int.tryParse(query);
if (number != null && number >= 0 && number < _sessionWords.length) {
final exact = _sessionWords[number];
final matches = _sessionWords.where((w) {
if (w.sessionNumber == number) return false;
final idStr = w.sessionNumber.toString();
final paddedStr = w.formattedSessionNumber;
return idStr.startsWith(query) || paddedStr.startsWith(query);
}).take(30).toList();
return [exact, ...matches];
return [_sessionWords[number]];
}
// Partial numeric match
if (RegExp(r'^\d+$').hasMatch(query)) {
return _sessionWords.where((w) {
final idStr = w.sessionNumber.toString();
final paddedStr = w.formattedSessionNumber;
return idStr.startsWith(query) || paddedStr.startsWith(query);
}).take(30).toList();
}
// Text search in word, description, category, and part of speech
final exact = <WordItem>[];
final startsWith = <WordItem>[];
final contains = <WordItem>[];
@@ -156,21 +120,29 @@ class WordsRepository {
return set.toList();
}
// --- History Management ---
// --- Session History Management ---
Future<void> addHistoryEntry(HistoryEntry entry) async {
_history.insert(0, entry);
if (_history.length > 500) {
_history.removeRange(500, _history.length);
Future<void> saveSession(OracleSession session) async {
final existingIdx = _sessions.indexWhere((s) => s.id == session.id);
if (existingIdx != -1) {
_sessions[existingIdx] = session;
} else {
_sessions.insert(0, session);
}
if (_sessions.length > 500) {
_sessions.removeRange(500, _sessions.length);
}
await _saveHistoryToPrefs();
}
Future<void> updateHistoryEntry(String id, {String? aiInterpretation, String? question}) async {
final idx = _history.indexWhere((e) => e.id == id);
// Backward compatibility alias
Future<void> addHistoryEntry(OracleSession entry) => saveSession(entry);
Future<void> updateSession(String id, {String? aiInterpretation, String? question}) async {
final idx = _sessions.indexWhere((e) => e.id == id);
if (idx != -1) {
final old = _history[idx];
_history[idx] = old.copyWith(
final old = _sessions[idx];
_sessions[idx] = old.copyWith(
aiInterpretation: aiInterpretation ?? old.aiInterpretation,
question: question ?? old.question,
);
@@ -178,21 +150,41 @@ class WordsRepository {
}
}
Future<void> deleteHistoryEntry(String id) async {
_history.removeWhere((e) => e.id == id);
Future<void> updateHistoryEntry(String id, {String? aiInterpretation, String? question}) =>
updateSession(id, aiInterpretation: aiInterpretation, question: question);
Future<void> deleteSession(String id) async {
_sessions.removeWhere((e) => e.id == id);
await _saveHistoryToPrefs();
}
Future<void> deleteHistoryEntry(String id) => deleteSession(id);
Future<void> clearHistory() async {
_history.clear();
_sessions.clear();
await _saveHistoryToPrefs();
}
Future<void> _loadHistoryFromPrefs() async {
try {
final prefs = await SharedPreferences.getInstance();
final jsonList = prefs.getStringList(_kHistoryKey);
_sessions.clear();
if (jsonList != null) {
for (final item in jsonList) {
try {
_sessions.add(OracleSession.fromJson(item));
} catch (_) {}
}
}
} catch (_) {}
}
Future<void> _saveHistoryToPrefs() async {
try {
final prefs = await SharedPreferences.getInstance();
final list = _history.map((e) => jsonEncode(e.toMap())).toList();
await prefs.setStringList('oracle_history_entries', list);
final jsonList = _sessions.map((e) => e.toJson()).toList();
await prefs.setStringList(_kHistoryKey, jsonList);
} catch (_) {}
}
}