This commit is contained in:
2026-05-05 16:57:00 +01:00
parent 8c9bdc551a
commit fc4dac1e14

View File

@@ -23,7 +23,7 @@ import java.util.concurrent.Executors;
public class InvoiceScannerHelper { public class InvoiceScannerHelper {
private static final String API_KEY = "YOUR_GEMINI_API_KEY_HERE"; // Substitua pela sua chave API private static final String API_KEY = "AIzaSyCoUZSXfEk43LfPtkCCjsnQ_ZMWX7NG1xQ"; // Substitua pela sua chave API
private static final String PROMPT = "Analisa esta fatura. Devolve APENAS um objeto JSON com os campos: 'valor' (Double, apenas números e ponto decimal), 'descricao' (String curta, nome do estabelecimento ou produto), 'categoria' (String, ex: Alimentação, Transporte, Lazer, Saúde, Casa, Educação, Outros), e 'data' (String formato DD/MM/AAAA). Se não conseguires ler algum, coloca valor padrão ou string vazia."; private static final String PROMPT = "Analisa esta fatura. Devolve APENAS um objeto JSON com os campos: 'valor' (Double, apenas números e ponto decimal), 'descricao' (String curta, nome do estabelecimento ou produto), 'categoria' (String, ex: Alimentação, Transporte, Lazer, Saúde, Casa, Educação, Outros), e 'data' (String formato DD/MM/AAAA). Se não conseguires ler algum, coloca valor padrão ou string vazia.";
public interface ScanCallback { public interface ScanCallback {
@@ -32,15 +32,20 @@ public class InvoiceScannerHelper {
} }
public static void scanInvoice(Context context, Uri imageUri, ScanCallback callback) { public static void scanInvoice(Context context, Uri imageUri, ScanCallback callback) {
if (API_KEY.equals("YOUR_GEMINI_API_KEY_HERE")) { if (API_KEY == null || API_KEY.isEmpty() || API_KEY.contains("YOUR_GEMINI_API_KEY")) {
callback.onError("Chave API do Gemini não configurada."); callback.onError("Chave API do Gemini não configurada.");
return; return;
} }
try { Executor executor = Executors.newSingleThreadExecutor();
InputStream imageStream = context.getContentResolver().openInputStream(imageUri); try (InputStream imageStream = context.getContentResolver().openInputStream(imageUri)) {
Bitmap bitmap = BitmapFactory.decodeStream(imageStream); Bitmap bitmap = BitmapFactory.decodeStream(imageStream);
if (bitmap == null) {
callback.onError("Não foi possível carregar a imagem da fatura.");
return;
}
GenerativeModel gm = new GenerativeModel( GenerativeModel gm = new GenerativeModel(
"gemini-1.5-flash", "gemini-1.5-flash",
API_KEY API_KEY
@@ -52,7 +57,6 @@ public class InvoiceScannerHelper {
.addImage(bitmap) .addImage(bitmap)
.build(); .build();
Executor executor = Executors.newSingleThreadExecutor();
ListenableFuture<GenerateContentResponse> response = model.generateContent(content); ListenableFuture<GenerateContentResponse> response = model.generateContent(content);
Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() { Futures.addCallback(response, new FutureCallback<GenerateContentResponse>() {
@@ -74,6 +78,10 @@ public class InvoiceScannerHelper {
} catch (JSONException e) { } catch (JSONException e) {
Log.e("InvoiceScanner", "Erro ao fazer parse do JSON: " + result.getText(), e); Log.e("InvoiceScanner", "Erro ao fazer parse do JSON: " + result.getText(), e);
callback.onError("Erro ao ler dados da fatura."); callback.onError("Erro ao ler dados da fatura.");
} finally {
if (executor instanceof java.util.concurrent.ExecutorService) {
((java.util.concurrent.ExecutorService) executor).shutdown();
}
} }
} }
@@ -81,12 +89,18 @@ public class InvoiceScannerHelper {
public void onFailure(Throwable t) { public void onFailure(Throwable t) {
Log.e("InvoiceScanner", "Falha na API do Gemini", t); Log.e("InvoiceScanner", "Falha na API do Gemini", t);
callback.onError("Falha ao comunicar com a IA: " + t.getMessage()); callback.onError("Falha ao comunicar com a IA: " + t.getMessage());
if (executor instanceof java.util.concurrent.ExecutorService) {
((java.util.concurrent.ExecutorService) executor).shutdown();
}
} }
}, executor); }, executor);
} catch (Exception e) { } catch (Exception e) {
e.printStackTrace(); Log.e("InvoiceScanner", "Erro geral", e);
callback.onError("Erro ao processar imagem: " + e.getMessage()); callback.onError("Erro ao processar imagem: " + e.getMessage());
if (executor instanceof java.util.concurrent.ExecutorService) {
((java.util.concurrent.ExecutorService) executor).shutdown();
}
} }
} }
} }