Compare commits

..

5 Commits

Author SHA1 Message Date
Ponshu Developer 073e55cc51 chore: update download page to v1.0.49 2026-04-23 22:32:46 +09:00
Ponshu Developer 856e349848 fix(ai): フォールバックモデルをgemini-2.0-flash(廃止)→gemini-2.5-flash-liteに変更
gemini-2.0-flashはdeprecated済みで、primary(gemini-2.5-flash)が3回失敗した際に
廃止済みモデルへ落ちて確実にエラーになっていた。フォールバックを現役の
gemini-2.5-flash-liteに変更することで「解析に失敗しました」を解消する。

また、エラーメッセージにHTTPステータスコード等の短い補足を追加し、
次回の障害診断を容易にする(例: [404] [key?] [timeout])。

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 22:25:12 +09:00
Ponshu Developer 778d2a725a fix(ai): 2段階解析のバグ2件修正
- Stage1でname/brandが両方nullの場合は無意味なStage2をスキップして1段階フォールバック
- nameJson/brandJsonをjsonEncode()でエスケープ(特殊文字含む銘柄名でのプロンプト破壊を防止)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 17:05:55 +09:00
Ponshu Developer bcba78a533 feat(ai): Gemini 2段階解析実装(OCR→フル解析)でhallucination低減
Stage1でOCR専念(name/brand/prefecture確定)、Stage2で確定済み制約を
プロンプトに埋め込み残フィールドを推定する2段階フロー。
東魁→東魁盛のような銘柄補完hallucination緩和が目的。

- 直接APIモード(consumer APK)のみ2段階。プロキシ/キャッシュは従来通り。
- Stage1失敗時は1段階フォールバック(堅牢性維持)
- AnalyzingDialog: stageNotifier対応・ステップ1/2のメッセージ切り替え表示
- APIコール数は実質2倍(1日20回→実質10回相当)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-04-23 16:37:57 +09:00
Ponshu Developer a5a5f729fe chore: bump to v1.0.47, update download page 2026-04-23 13:11:40 +09:00
10 changed files with 556 additions and 217 deletions

View File

@ -124,18 +124,27 @@ mixin CameraAnalysisMixin<T extends ConsumerStatefulWidget> on ConsumerState<T>
// :
if (!mounted) return;
final stageNotifier = ValueNotifier<int>(1);
var stageNotifierDisposed = false;
// ignore: use_build_context_synchronously
// mounted BuildContext
showDialog(
context: context,
barrierDismissible: false,
builder: (context) => const AnalyzingDialog(),
builder: (context) => AnalyzingDialog(stageNotifier: stageNotifier),
);
try {
debugPrint('Starting Gemini Vision Direct Analysis for ${capturedImages.length} images');
debugPrint('Starting Gemini 2-stage analysis for ${capturedImages.length} images');
final geminiService = ref.read(geminiServiceProvider);
final result = await geminiService.analyzeSakeLabel(capturedImages);
final result = await geminiService.analyzeSakeLabel(
capturedImages,
onStep1Complete: () {
if (!stageNotifierDisposed) stageNotifier.value = 2;
},
);
// Create SakeItem (Schema v2.0)
final sakeItem = SakeItem(
@ -372,17 +381,38 @@ mixin CameraAnalysisMixin<T extends ConsumerStatefulWidget> on ConsumerState<T>
}
debugPrint('Analysis error: $e');
final errDetail = _extractErrorCode(e.toString());
messenger.showSnackBar(
SnackBar(
content: const Text('解析に失敗しました。時間をおいて再試行してください。'),
content: Text('解析に失敗しました。時間をおいて再試行してください。$errDetail'),
duration: const Duration(seconds: 5),
backgroundColor: appColors.error,
),
);
}
} finally {
stageNotifierDisposed = true;
stageNotifier.dispose();
}
}
/// HTTP
///
String _extractErrorCode(String err) {
final patterns = {
RegExp(r'\b(4\d{2}|5\d{2})\b'): (Match m) => ' [${m.group(0)}]',
RegExp(r'API_KEY_INVALID|PERMISSION_DENIED'): (_) => ' [key?]',
RegExp(r'RESOURCE_EXHAUSTED'): (_) => ' [quota]',
RegExp(r'NOT_FOUND'): (_) => ' [model?]',
RegExp(r'timeout', caseSensitive: false): (_) => ' [timeout]',
};
for (final entry in patterns.entries) {
final m = entry.key.firstMatch(err);
if (m != null) return entry.value(m);
}
return '';
}
///
///
///

View File

@ -358,6 +358,15 @@ class _PendingAnalysisScreenState extends ConsumerState<PendingAnalysisScreen> {
width: 60,
height: 60,
fit: BoxFit.cover,
errorBuilder: (_, __, ___) => Container(
width: 60,
height: 60,
decoration: BoxDecoration(
color: appColors.divider,
borderRadius: BorderRadius.circular(8),
),
child: Icon(LucideIcons.image, color: appColors.iconSubtle),
),
),
)
: Container(

View File

@ -2,6 +2,7 @@ import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../providers/theme_provider.dart';
import '../theme/app_colors.dart';
import '../widgets/settings/display_settings_section.dart';
import '../widgets/settings/other_settings_section.dart';
import '../widgets/settings/backup_settings_section.dart';
@ -22,7 +23,7 @@ class _ShopSettingsScreenState extends ConsumerState<ShopSettingsScreen> {
@override
Widget build(BuildContext context) {
final userProfile = ref.watch(userProfileProvider);
final isDark = Theme.of(context).brightness == Brightness.dark;
final appColors = Theme.of(context).extension<AppColors>()!;
return Scaffold(
appBar: AppBar(
@ -35,9 +36,9 @@ class _ShopSettingsScreenState extends ConsumerState<ShopSettingsScreen> {
// Business Config Section
_buildSectionHeader(context, '価格設定', LucideIcons.briefcase),
Card(
color: isDark ? const Color(0xFF1E1E1E) : null,
color: appColors.surfaceElevated,
child: ListTile(
leading: Icon(LucideIcons.percent, color: isDark ? Colors.orange[300] : Theme.of(context).primaryColor),
leading: Icon(LucideIcons.percent, color: appColors.iconAccent),
title: const Text('基本掛率'),
trailing: Row(
mainAxisSize: MainAxisSize.min,
@ -45,15 +46,15 @@ class _ShopSettingsScreenState extends ConsumerState<ShopSettingsScreen> {
Text('×', style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 16,
color: isDark ? Colors.grey[400] : Colors.grey[600],
color: appColors.textSecondary,
)),
const SizedBox(width: 8),
Container(
padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 4),
decoration: BoxDecoration(
color: isDark ? Colors.grey[800] : Colors.grey[100],
color: appColors.surfaceSubtle,
borderRadius: BorderRadius.circular(8),
border: Border.all(color: isDark ? Colors.grey[700]! : Colors.grey[300]!),
border: Border.all(color: appColors.divider),
),
child: DropdownButton<double>(
value: userProfile.defaultMarkup,
@ -96,18 +97,18 @@ class _ShopSettingsScreenState extends ConsumerState<ShopSettingsScreen> {
}
Widget _buildSectionHeader(BuildContext context, String title, IconData icon) {
final isDark = Theme.of(context).brightness == Brightness.dark;
final appColors = Theme.of(context).extension<AppColors>()!;
return Padding(
padding: const EdgeInsets.symmetric(vertical: 8, horizontal: 4),
child: Row(
children: [
Icon(icon, size: 20, color: isDark ? Colors.orange[300] : Theme.of(context).primaryColor),
Icon(icon, size: 20, color: appColors.iconAccent),
const SizedBox(width: 8),
Text(
title,
style: Theme.of(context).textTheme.titleMedium?.copyWith(
fontWeight: FontWeight.bold,
color: isDark ? Colors.grey[300] : Theme.of(context).primaryColor,
color: appColors.textPrimary,
),
),
],

View File

@ -11,6 +11,15 @@ import 'package:path_provider/path_provider.dart';
import 'package:path/path.dart' as path;
import '../models/sake_item.dart';
///
/// UI /使
class PreRestoreBackupException implements Exception {
const PreRestoreBackupException();
@override
String toString() => 'PreRestoreBackupException: pre-restore safety backup failed';
}
/// Google Driveへのバックアップ
///
///
@ -325,8 +334,11 @@ class BackupService {
final driveApi = drive.DriveApi(authClient);
// 3. 退
await _createPreRestoreBackup();
// 3. 退
final preBackupOk = await _createPreRestoreBackup();
if (!preBackupOk) {
throw const PreRestoreBackupException();
}
// 4. Google Driveからダウンロード
final zipFile = await _downloadFromDrive(driveApi);
@ -342,26 +354,55 @@ class BackupService {
await zipFile.delete();
return success;
} on PreRestoreBackupException {
rethrow;
} catch (error) {
debugPrint('[RESTORE] Restore error: $error');
return false;
}
}
/// 退
Future<void> _createPreRestoreBackup() async {
/// 退 true false
Future<bool> _createPreRestoreBackup() async {
try {
final tempDir = await getTemporaryDirectory();
final backupPath = path.join(tempDir.path, 'pre_restore_backup.zip');
final zipFile = await _createBackupZip();
if (zipFile != null) {
if (zipFile == null) {
debugPrint('[RESTORE] Pre-restore backup: ZIP creation failed');
return false;
}
await zipFile.copy(backupPath);
await zipFile.delete();
debugPrint('[RESTORE] Pre-restore backup saved: $backupPath');
}
return true;
} catch (error) {
debugPrint('[RESTORE] Pre-restore backup error: $error');
return false;
}
}
///
Future<bool> restoreBackupSkippingPreBackup() async {
try {
final account = _googleSignIn.currentUser;
if (account == null) return false;
final authClient = await _googleSignIn.authenticatedClient();
if (authClient == null) return false;
final driveApi = drive.DriveApi(authClient);
final zipFile = await _downloadFromDrive(driveApi);
if (zipFile == null) return false;
final success = await _restoreFromZip(zipFile);
await zipFile.delete();
return success;
} catch (error) {
debugPrint('[RESTORE] Force restore error: $error');
return false;
}
}
@ -393,7 +434,14 @@ class BackupService {
// 3.
final sink = downloadFile.openWrite();
await media.stream.pipe(sink);
await media.stream.pipe(sink).timeout(
const Duration(minutes: 3),
onTimeout: () {
sink.close();
try { downloadFile.deleteSync(); } catch (_) {}
throw TimeoutException('Backup download timed out after 3 minutes');
},
);
debugPrint('[RESTORE] Download complete: $downloadPath');
return downloadFile;
@ -484,7 +532,7 @@ class BackupService {
isUserEdited: data['userData']['isUserEdited'] as bool,
price: data['userData']['price'] as int?,
costPrice: data['userData']['costPrice'] as int?,
markup: (data['userData']['markup'] as num).toDouble(),
markup: (data['userData']['markup'] as num?)?.toDouble() ?? 3.0,
priceVariants: data['userData']['priceVariants'] != null
? Map<String, int>.from(data['userData']['priceVariants'] as Map)
: null,

View File

@ -13,16 +13,280 @@ class GeminiService {
// AI Proxy Server Configuration
static final String _proxyUrl = Secrets.aiProxyAnalyzeUrl;
// ? Proxy側で管理されているが
static DateTime? _lastApiCallTime;
static const Duration _minApiInterval = Duration(seconds: 2);
GeminiService();
///
Future<SakeAnalysisResult> analyzeSakeLabel(List<String> imagePaths, {bool forceRefresh = false}) async {
//
const prompt = '''
// ============================================================
// Public API
// ============================================================
/// 2: OCR
///
/// [onStep1Complete]: Stage 1
/// UI 2使
/// APIモードconsumer APK1
Future<SakeAnalysisResult> analyzeSakeLabel(
List<String> imagePaths, {
bool forceRefresh = false,
VoidCallback? onStep1Complete,
}) async {
if (Secrets.useProxy) {
return _callProxyApi(
imagePaths: imagePaths,
customPrompt: _mainAnalysisPrompt,
forceRefresh: forceRefresh,
);
}
return _runTwoStageAnalysis(
imagePaths,
forceRefresh: forceRefresh,
onStep1Complete: onStep1Complete,
);
}
/// :
Future<SakeAnalysisResult> reanalyzeSakeLabel(
List<String> imagePaths, {
String? previousName,
String? previousBrand,
}) async {
final prevNameStr = previousName != null ? '$previousName' : '不明';
final prevBrandStr = previousBrand != null ? '$previousBrand' : '不明';
final challengePrompt = '''
:
- name: $prevNameStr
- brand: $prevBrandStr
##
1. 1
2. name=$prevNameStr
3.
4. N N
## namebrandprefectureの読み取りOCR厳守
-
-
- /
- prefecture null
##
使
##
JSONのみ返す:
{
"name": "ラベルに写っている銘柄名(補完禁止)",
"brand": "ラベルに写っている蔵元名(補完禁止)",
"prefecture": "ラベルに書かれた都道府県名なければnull",
"type": "特定名称なければnull",
"description": "説明文100文字程度",
"catchCopy": "20文字以内のキャッチコピー",
"confidenceScore": 80,
"flavorTags": ["フルーティー", "辛口"],
"tasteStats": {"aroma":3,"sweetness":3,"acidity":3,"bitterness":3,"body":3},
"alcoholContent": 15.0,
"polishingRatio": 50,
"sakeMeterValue": 3.0,
"riceVariety": null,
"yeast": null,
"manufacturingYearMonth": null
}
''';
return _callDirectApi(
imagePaths,
challengePrompt,
forceRefresh: true,
temperature: 0.3,
);
}
// ============================================================
// 2APIモード専用
// ============================================================
/// Stage1(OCR) Stage2() 2
Future<SakeAnalysisResult> _runTwoStageAnalysis(
List<String> imagePaths, {
bool forceRefresh = false,
VoidCallback? onStep1Complete,
}) async {
// Stage1実行前にキャッシュ確認 API
if (!forceRefresh && imagePaths.isNotEmpty) {
final imageHash = await AnalysisCacheService.computeCombinedHash(imagePaths);
final cached = await AnalysisCacheService.getCached(imageHash);
if (cached != null) {
debugPrint('2-stage: cache hit, skipping API calls');
return cached.asCached();
}
}
final apiKey = Secrets.geminiApiKey;
if (apiKey.isEmpty) throw Exception('Gemini API Key is missing. Please set GEMINI_API_KEY.');
// Stage1/2I/O節約
final imageParts = <DataPart>[];
for (final path in imagePaths) {
final bytes = await File(path).readAsBytes();
imageParts.add(DataPart('image/jpeg', bytes));
debugPrint('Loaded image for 2-stage: ${(bytes.length / 1024).toStringAsFixed(1)}KB');
}
// --- Stage 1: OCR専念301---
Map<String, String?> ocr;
try {
ocr = await _performOcrStep(apiKey, imageParts);
debugPrint('Stage1 OCR: name="${ocr['name']}" brand="${ocr['brand']}" pref="${ocr['prefecture']}"');
} catch (e) {
debugPrint('Stage1 OCR failed ($e), falling back to single-stage');
return _callDirectApi(imagePaths, null, forceRefresh: forceRefresh);
}
// Stage1 name/brand null = 2
if (ocr['name'] == null && ocr['brand'] == null) {
debugPrint('Stage1 returned no text, falling back to single-stage');
return _callDirectApi(imagePaths, null, forceRefresh: forceRefresh);
}
// Stage 1 UI AnalyzingDialog Stage2
onStep1Complete?.call();
// --- Stage 2: OCR結果を制約として渡し ---
// _callDirectApi Stage2
// forceRefresh=false
//
final stage2Prompt = _buildStage2Prompt(ocr);
return _callDirectApi(imagePaths, stage2Prompt, forceRefresh: forceRefresh);
}
/// Stage 1: OCRのみ実行name / brand / prefecture
///
///
/// rethrow
Future<Map<String, String?>> _performOcrStep(
String apiKey,
List<DataPart> imageParts,
) async {
const ocrPrompt = '''
3OCRしてください
-
- :
- N文字しかなければN文字のみ出力する
JSONのみ返す:
{"name": "銘柄名", "brand": "蔵元名", "prefecture": "都道府県名またはnull"}
''';
final model = GenerativeModel(
model: 'gemini-2.5-flash',
apiKey: apiKey,
systemInstruction: Content.system(
'あなたはOCR専用システムです。ラベルの文字を一字一句正確に書き起こすだけです。'
'銘柄名の補完・変換・拡張は厳禁。見えている文字数と出力文字数を一致させること。',
),
generationConfig: GenerationConfig(
responseMimeType: 'application/json',
temperature: 0,
),
);
final parts = <Part>[TextPart(ocrPrompt), ...imageParts];
final response = await model
.generateContent([Content.multi(parts)])
.timeout(const Duration(seconds: 30));
final jsonStr = response.text;
if (jsonStr == null || jsonStr.isEmpty) {
throw Exception('Stage1: empty response');
}
final map = jsonDecode(jsonStr) as Map<String, dynamic>;
return {
'name': map['name'] as String?,
'brand': map['brand'] as String?,
'prefecture': map['prefecture'] as String?,
};
}
/// Stage 2 : Stage 1 OCR
///
/// Gemini name/brand/prefecture
/// hallucination
String _buildStage2Prompt(Map<String, String?> ocr) {
final name = ocr['name'];
final brand = ocr['brand'];
final prefecture = ocr['prefecture'];
final nameConstraint = name != null ? '$name」(確定済み — 変更禁止)' : 'null確定済み';
final brandConstraint = brand != null ? '$brand」(確定済み — 変更禁止)' : 'null確定済み';
final prefConstraint = prefecture != null ? '$prefecture」(確定済み — 変更禁止)' : 'null確定済み';
final nameJson = name != null ? jsonEncode(name) : 'null';
final brandJson = brand != null ? jsonEncode(brand) : 'null';
final prefJson = prefecture != null ? jsonEncode(prefecture) : 'null';
return '''
1OCR結果 3
OCRした確定結果です
- name: $nameConstraint
- brand: $brandConstraint
- prefecture: $prefConstraint
3JSONに含め
##
- type: null
- description: type 100
- catchCopy: 20
- flavorTags:
- tasteStats: 15 3
- alcoholContent: type
- polishingRatio: type
- sakeMeterValue:
- riceVariety: null
- yeast: null
- manufacturingYearMonth: null
- confidenceScore: 0100
##
JSONのみ返す:
{
"name": $nameJson,
"brand": $brandJson,
"prefecture": $prefJson,
"type": "特定名称なければnull",
"description": "説明文100文字程度",
"catchCopy": "20文字以内のキャッチコピー",
"confidenceScore": 80,
"flavorTags": ["フルーティー", "辛口"],
"tasteStats": {"aroma":3,"sweetness":3,"acidity":3,"bitterness":3,"body":3},
"alcoholContent": 15.0,
"polishingRatio": 50,
"sakeMeterValue": 3.0,
"riceVariety": null,
"yeast": null,
"manufacturingYearMonth": null
}
''';
}
// ============================================================
// 1
// ============================================================
static const String _mainAnalysisPrompt = '''
JSONを返してください
@ -86,93 +350,15 @@ name・brand を出力する直前に以下を確認してください:
}
''';
return _callProxyApi(
imagePaths: imagePaths,
customPrompt: prompt, // Override server default
forceRefresh: forceRefresh,
);
}
// ============================================================
// APIコールiOSビルド用 / USE_PROXY=true
// ============================================================
/// :
///
/// analyzeSakeLabel :
/// - name/brand
/// - temperature=0.3
/// - hallucination
Future<SakeAnalysisResult> reanalyzeSakeLabel(
List<String> imagePaths, {
String? previousName,
String? previousBrand,
}) async {
final prevNameStr = previousName != null ? '$previousName' : '不明';
final prevBrandStr = previousBrand != null ? '$previousBrand' : '不明';
final challengePrompt = '''
:
- name: $prevNameStr
- brand: $prevBrandStr
##
1. 1
2. name=$prevNameStr
3.
4. N N
## namebrandprefectureの読み取りOCR厳守
-
-
- /
- prefecture null
##
使
##
JSONのみ返す:
{
"name": "ラベルに写っている銘柄名(補完禁止)",
"brand": "ラベルに写っている蔵元名(補完禁止)",
"prefecture": "ラベルに書かれた都道府県名なければnull",
"type": "特定名称なければnull",
"description": "説明文100文字程度",
"catchCopy": "20文字以内のキャッチコピー",
"confidenceScore": 80,
"flavorTags": ["フルーティー", "辛口"],
"tasteStats": {"aroma":3,"sweetness":3,"acidity":3,"bitterness":3,"body":3},
"alcoholContent": 15.0,
"polishingRatio": 50,
"sakeMeterValue": 3.0,
"riceVariety": null,
"yeast": null,
"manufacturingYearMonth": null
}
''';
return _callDirectApi(
imagePaths,
challengePrompt,
forceRefresh: true,
temperature: 0.3,
);
}
/// : ProxyへのAPIコール
Future<SakeAnalysisResult> _callProxyApi({
required List<String> imagePaths,
String? customPrompt,
bool forceRefresh = false,
}) async {
// Check Mode: Direct vs Proxy
if (!Secrets.useProxy) {
debugPrint('Direct Cloud Mode: Connecting to Gemini API directly...');
return _callDirectApi(imagePaths, customPrompt, forceRefresh: forceRefresh);
}
// 1. forceRefresh=false
if (!forceRefresh && imagePaths.isNotEmpty) {
final imageHash = await AnalysisCacheService.computeCombinedHash(imagePaths);
@ -193,21 +379,20 @@ name・brand を出力する直前に以下を確認してください:
}
_lastApiCallTime = DateTime.now();
// 2. Base64変換
// 3. Base64変換
List<String> base64Images = [];
for (final path in imagePaths) {
// Read already-compressed images directly (compressed at capture time)
final bytes = await File(path).readAsBytes();
final base64String = base64Encode(bytes);
base64Images.add(base64String);
debugPrint('Encoded processed image: ${(bytes.length / 1024).toStringAsFixed(1)}KB');
}
// 3. ID取得
// 4. ID取得
final deviceId = await DeviceService.getDeviceId();
if (kDebugMode) debugPrint('Device ID: $deviceId');
// 4.
// 5.
final requestBody = jsonEncode({
"device_id": deviceId,
"images": base64Images,
@ -216,7 +401,7 @@ name・brand を出力する直前に以下を確認してください:
debugPrint('Calling Proxy: $_proxyUrl');
// 5. Bearer Token認証付き
// 6. Bearer Token認証付き
final headers = {
"Content-Type": "application/json",
if (Secrets.proxyAuthToken.isNotEmpty)
@ -226,18 +411,16 @@ name・brand を出力する直前に以下を確認してください:
Uri.parse(_proxyUrl),
headers: headers,
body: requestBody,
).timeout(const Duration(seconds: 60)); // : 60 ()
).timeout(const Duration(seconds: 60));
// 6.
// 7.
if (response.statusCode == 200) {
// : { "success": true, "data": {...}, "usage": {...} }
final jsonResponse = jsonDecode(utf8.decode(response.bodyBytes));
if (jsonResponse['success'] == true) {
final data = jsonResponse['data'];
if (data == null) throw Exception("サーバーからのデータが空です");
// 使
if (jsonResponse['usage'] != null) {
final usage = jsonResponse['usage'];
debugPrint('API Usage: ${usage['today']}/${usage['limit']}');
@ -245,9 +428,6 @@ name・brand を出力する直前に以下を確認してください:
final result = SakeAnalysisResult.fromJson(data);
// tasteStats SakeAnalysisResult.fromJson
// API不使用
if (imagePaths.isNotEmpty) {
final imageHash = await AnalysisCacheService.computeCombinedHash(imagePaths);
await AnalysisCacheService.saveCache(imageHash, result);
@ -260,11 +440,9 @@ name・brand を出力する直前に以下を確認してください:
return result;
} else {
// Proxy側での論理エラー ()
throw Exception(jsonResponse['error'] ?? '不明なエラーが発生しました');
}
} else {
// HTTPエラー
if (kDebugMode) {
debugPrint('Proxy Error: ${response.statusCode} ${response.body}');
}
@ -273,7 +451,6 @@ name・brand を出力する直前に以下を確認してください:
} catch (e) {
debugPrint('Proxy Call Failed: $e');
//
final errorMsg = e.toString().toLowerCase();
if (errorMsg.contains('limit') || errorMsg.contains('上限')) {
throw Exception('本日のAI解析リクエスト上限に達しました。\n明日またお試しください。');
@ -282,10 +459,16 @@ name・brand を出力する直前に以下を確認してください:
}
}
/// Direct Cloud API Implementation (No Proxy)
Future<SakeAnalysisResult> _callDirectApi(List<String> imagePaths, String? customPrompt, {bool forceRefresh = false, double temperature = 0}) async {
// 1.
// forceRefresh=trueの場合はキャッシュをスキップ
// ============================================================
// APIコールconsumer APK / USE_PROXY=false
// ============================================================
Future<SakeAnalysisResult> _callDirectApi(
List<String> imagePaths,
String? customPrompt, {
bool forceRefresh = false,
double temperature = 0,
}) async {
if (!forceRefresh && imagePaths.isNotEmpty) {
final imageHash = await AnalysisCacheService.computeCombinedHash(imagePaths);
final cached = await AnalysisCacheService.getCached(imageHash);
@ -295,65 +478,22 @@ name・brand を出力する直前に以下を確認してください:
}
}
// 2. API Key確認
final apiKey = Secrets.geminiApiKey;
if (apiKey.isEmpty) {
throw Exception('Gemini API Key is missing. Please set GEMINI_API_KEY.');
}
// : 503/UNAVAILABLE
// NOTE: Google
// Phase 2
const primaryModel = 'gemini-2.5-flash';
const fallbackModel = 'gemini-2.0-flash';
const fallbackModel = 'gemini-2.5-flash-lite';
// customPrompt analyzeSakeLabel null
final promptText = customPrompt ?? '''
JSONを返してください
final promptText = customPrompt ?? _mainAnalysisPrompt;
## namebrandprefectureの読み取りOCR厳守
3
/ / 鹿鹿
N N
- prefecture: null
##
使
- tasteStats: 15 3
- alcoholContentpolishingRatio: type
##
JSONのみ返す:
{
"name": "ラベルに写っている銘柄名の文字(一字一句そのまま・補完禁止)",
"brand": "ラベルに写っている蔵元名の文字(一字一句そのまま・補完禁止)",
"prefecture": "ラベルに書かれた都道府県名なければnull・推測禁止",
"type": "特定名称ラベルから読む。なければnull",
"description": "ラベル情報とtypeから推定した説明文100文字程度",
"catchCopy": "20文字以内のキャッチコピー",
"confidenceScore": 80,
"flavorTags": ["フルーティー", "辛口"],
"tasteStats": {"aroma":3,"sweetness":3,"acidity":3,"bitterness":3,"body":3},
"alcoholContent": 15.0,
"polishingRatio": 50,
"sakeMeterValue": 3.0,
"riceVariety": "山田錦",
"yeast": "きょうかい9号",
"manufacturingYearMonth": "2023.10"
}
''';
// Prepare Content parts ()
final contentParts = <Part>[TextPart(promptText)];
for (var path in imagePaths) {
final bytes = await File(path).readAsBytes();
contentParts.add(DataPart('image/jpeg', bytes));
}
// 503 :
const maxRetries = 3;
final modelsToTry = [primaryModel, primaryModel, primaryModel, fallbackModel];
@ -398,11 +538,9 @@ name・brand を出力する直前に以下を確認してください:
final jsonMap = jsonDecode(jsonString);
final result = SakeAnalysisResult.fromJson(jsonMap);
// 3.
if (imagePaths.isNotEmpty) {
final imageHash = await AnalysisCacheService.computeCombinedHash(imagePaths);
await AnalysisCacheService.saveCache(imageHash, result);
// 4. forceRefresh
await AnalysisCacheService.registerBrandIndex(
result.name,
imageHash,
@ -419,22 +557,20 @@ name・brand を出力する直前に以下を確認してください:
debugPrint('Direct API Error (attempt $attempt, model: $modelName): $e');
if (isLastAttempt || !is503) {
// or 503
if (is503) {
throw const GeminiCongestionException();
}
if (is503) throw const GeminiCongestionException();
throw Exception('AI解析エラー(Direct): $e');
}
// 503
}
}
//
throw Exception('AI解析に失敗しました。再試行してください。');
}
}
// Analysis Result Model
// ============================================================
// Data Models
// ============================================================
class SakeAnalysisResult {
final String? name;
final String? brand;
@ -446,7 +582,6 @@ class SakeAnalysisResult {
final List<String> flavorTags;
final Map<String, int> tasteStats;
// New Fields
final double? alcoholContent;
final int? polishingRatio;
final double? sakeMeterValue;
@ -455,7 +590,6 @@ class SakeAnalysisResult {
final String? manufacturingYearMonth;
/// EXP付与使
/// JSON false
final bool isFromCache;
SakeAnalysisResult({
@ -477,7 +611,6 @@ class SakeAnalysisResult {
this.isFromCache = false,
});
///
SakeAnalysisResult asCached() => SakeAnalysisResult(
name: name, brand: brand, prefecture: prefecture, type: type,
description: description, catchCopy: catchCopy, confidenceScore: confidenceScore,
@ -489,7 +622,6 @@ class SakeAnalysisResult {
);
factory SakeAnalysisResult.fromJson(Map<String, dynamic> json) {
// tasteStats: 3 (15)
const requiredStatKeys = ['aroma', 'sweetness', 'acidity', 'bitterness', 'body'];
Map<String, int> stats = {};
if (json['tasteStats'] is Map) {
@ -522,7 +654,6 @@ class SakeAnalysisResult {
);
}
/// JSON形式に変換
Map<String, dynamic> toJson() {
return {
'name': name,

View File

@ -2,7 +2,12 @@ import 'package:flutter/material.dart';
import 'dart:async';
class AnalyzingDialog extends StatefulWidget {
const AnalyzingDialog({super.key});
/// Stage ValueNotifier
/// null Stage1
/// value 2 Stage2
final ValueNotifier<int>? stageNotifier;
const AnalyzingDialog({super.key, this.stageNotifier});
@override
State<AnalyzingDialog> createState() => _AnalyzingDialogState();
@ -10,32 +15,70 @@ class AnalyzingDialog extends StatefulWidget {
class _AnalyzingDialogState extends State<AnalyzingDialog> {
int _messageIndex = 0;
Timer? _timer;
final List<String> _messages = [
'ラベルを読んでいます...',
'銘柄を確認しています...',
static const _stage1Messages = [
'ラベルを読み取っています...',
'文字を一字一句確認中...',
];
static const _stage2Messages = [
'この日本酒の個性を分析中...',
'フレーバーチャートを描画しています...',
'素敵なキャッチコピーを考えています...',
];
List<String> get _currentMessages =>
(_stage == 2) ? _stage2Messages : _stage1Messages;
int _stage = 1;
@override
void initState() {
super.initState();
widget.stageNotifier?.addListener(_onStageChanged);
_startMessageRotation();
}
void _startMessageRotation() {
Future.delayed(const Duration(milliseconds: 1500), () {
if (mounted && _messageIndex < _messages.length - 1) {
setState(() => _messageIndex++);
void _onStageChanged() {
final newStage = widget.stageNotifier?.value ?? 1;
if (newStage != _stage) {
_timer?.cancel();
setState(() {
_stage = newStage;
_messageIndex = 0;
});
_startMessageRotation();
}
}
void _startMessageRotation() {
_timer = Timer.periodic(const Duration(milliseconds: 1800), (timer) {
if (!mounted) {
timer.cancel();
return;
}
final messages = _currentMessages;
if (_messageIndex < messages.length - 1) {
setState(() => _messageIndex++);
} else {
timer.cancel();
}
});
}
@override
void dispose() {
_timer?.cancel();
widget.stageNotifier?.removeListener(_onStageChanged);
super.dispose();
}
@override
Widget build(BuildContext context) {
final messages = _currentMessages;
final safeIndex = _messageIndex.clamp(0, messages.length - 1);
return Dialog(
child: Padding(
padding: const EdgeInsets.all(24.0),
@ -45,10 +88,19 @@ class _AnalyzingDialogState extends State<AnalyzingDialog> {
const CircularProgressIndicator(),
const SizedBox(height: 24),
Text(
_messages[_messageIndex],
messages[safeIndex],
style: Theme.of(context).textTheme.titleMedium,
textAlign: TextAlign.center,
),
if (widget.stageNotifier != null) ...[
const SizedBox(height: 12),
Text(
'ステップ $_stage / 2',
style: Theme.of(context).textTheme.bodySmall?.copyWith(
color: Theme.of(context).colorScheme.onSurface.withValues(alpha: 0.4),
),
),
],
],
),
),

View File

@ -272,6 +272,7 @@ class _SakeDetailSpecsState extends State<SakeDetailSpecs> {
_isEditing,
suffixIcon: LucideIcons.calendar,
onSuffixTap: () => _showDatePicker(context),
helperText: '例: 2023-10',
),
],
),
@ -303,10 +304,11 @@ class _SakeDetailSpecsState extends State<SakeDetailSpecs> {
void _showDatePicker(BuildContext context) {
if (!_isEditing) return;
// Parse current value or use now
// Parse current value or use now (AI出力 "2023.10" "2023-10" )
DateTime initialDate = DateTime.now();
try {
final parts = _manufacturingController.text.split('-');
final normalized = _manufacturingController.text.replaceAll('.', '-');
final parts = normalized.split('-');
if (parts.length >= 2) {
final year = int.parse(parts[0]);
final month = int.parse(parts[1]);

View File

@ -1,9 +1,12 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:lucide_icons/lucide_icons.dart';
import '../../providers/sake_list_provider.dart';
import '../../providers/theme_provider.dart';
import '../../services/backup_service.dart';
import '../../theme/app_colors.dart';
class BackupSettingsSection extends StatefulWidget {
class BackupSettingsSection extends ConsumerStatefulWidget {
final String title;
const BackupSettingsSection({
@ -12,12 +15,12 @@ class BackupSettingsSection extends StatefulWidget {
});
@override
State<BackupSettingsSection> createState() => _BackupSettingsSectionState();
ConsumerState<BackupSettingsSection> createState() => _BackupSettingsSectionState();
}
enum _BackupState { idle, signingIn, signingOut, backingUp, restoring }
class _BackupSettingsSectionState extends State<BackupSettingsSection> {
class _BackupSettingsSectionState extends ConsumerState<BackupSettingsSection> {
final BackupService _backupService = BackupService();
_BackupState _state = _BackupState.idle;
@ -28,7 +31,11 @@ enum _BackupState { idle, signingIn, signingOut, backingUp, restoring }
}
Future<void> _initBackupService() async {
try {
await _backupService.init();
} catch (e) {
debugPrint('[Backup] Init error (silent sign-in failed): $e');
}
if (mounted) {
setState(() {});
}
@ -132,7 +139,7 @@ enum _BackupState { idle, signingIn, signingOut, backingUp, restoring }
Future<void> _restoreBackup() async {
final messenger = ScaffoldMessenger.of(context);
final appColors = Theme.of(context).extension<AppColors>()!;
// Note: hasBackup check is async
final hasBackup = await _backupService.hasBackupOnDrive();
if (!hasBackup) {
if (mounted) {
@ -173,11 +180,29 @@ enum _BackupState { idle, signingIn, signingOut, backingUp, restoring }
),
);
if (confirmed == true && mounted) {
if (confirmed != true || !mounted) return;
await _executeRestore(forceSkipPreBackup: false);
}
/// PreRestoreBackupException
Future<void> _executeRestore({required bool forceSkipPreBackup}) async {
final messenger = ScaffoldMessenger.of(context);
final appColors = Theme.of(context).extension<AppColors>()!;
setState(() => _state = _BackupState.restoring);
final success = await _backupService.restoreBackup();
try {
final success = forceSkipPreBackup
? await _backupService.restoreBackupSkippingPreBackup()
: await _backupService.restoreBackup();
if (mounted) {
setState(() => _state = _BackupState.idle);
if (success) {
ref.invalidate(rawSakeListItemsProvider);
ref.invalidate(sakeSortOrderProvider);
ref.invalidate(userProfileProvider);
}
messenger.showSnackBar(
SnackBar(
content: Text(success ? '復元が完了しました' : '復元に失敗しました'),
@ -185,6 +210,47 @@ enum _BackupState { idle, signingIn, signingOut, backingUp, restoring }
),
);
}
} on PreRestoreBackupException {
if (!mounted) return;
setState(() => _state = _BackupState.idle);
//
final continueAnyway = await showDialog<bool>(
context: context,
builder: (context) => AlertDialog(
title: Row(
children: [
Icon(LucideIcons.alertTriangle, color: appColors.error, size: 24),
const SizedBox(width: 8),
const Text('安全バックアップに失敗'),
],
),
content: const Text(
'復元前の安全コピー作成に失敗しました。\n'
'このまま続行すると、現在のデータが失われた場合に\n'
'元に戻せない可能性があります。\n\n'
'続行しますか?',
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context, false),
child: const Text('中断'),
),
ElevatedButton(
onPressed: () => Navigator.pop(context, true),
style: ElevatedButton.styleFrom(
backgroundColor: appColors.error,
foregroundColor: appColors.surfaceSubtle,
),
child: const Text('それでも続行'),
),
],
),
);
if (continueAnyway == true && mounted) {
await _executeRestore(forceSkipPreBackup: true);
}
}
}

View File

@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 1.0.47+54
version: 1.0.49+56
environment:
sdk: ^3.10.1

View File

@ -1,19 +1,19 @@
{
"version": "v1.0.46",
"name": "Ponshu Room 1.0.46 (2026-04-23)",
"version": "v1.0.49",
"name": "Ponshu Room 1.0.49 (2026-04-23)",
"date": "2026-04-23",
"apks": {
"maita": {
"lite": {
"filename": "ponshu_room_consumer_maita.apk",
"url": "https://posimai-lab.tail72e846.ts.net/mai/ponshu-room-lite/releases/download/v1.0.46/ponshu_room_consumer_maita.apk",
"url": "https://posimai-lab.tail72e846.ts.net/mai/ponshu-room-lite/releases/download/v1.0.49/ponshu_room_consumer_maita.apk",
"size_mb": 91
}
},
"eiji": {
"lite": {
"filename": "ponshu_room_consumer_eiji.apk",
"url": "https://posimai-lab.tail72e846.ts.net/mai/ponshu-room-lite/releases/download/v1.0.46/ponshu_room_consumer_eiji.apk",
"url": "https://posimai-lab.tail72e846.ts.net/mai/ponshu-room-lite/releases/download/v1.0.49/ponshu_room_consumer_eiji.apk",
"size_mb": 91
}
}