corrige o erro da camera e da ia não funcionar e mudar o layout futuramente

This commit is contained in:
2026-05-11 17:19:20 +01:00
parent e480abd98e
commit 1a8ddf4b79
20 changed files with 850 additions and 829 deletions

View File

@@ -2,6 +2,9 @@ package com.example.pap;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.ImageDecoder;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Base64;
@@ -14,6 +17,7 @@ import androidx.activity.result.contract.ActivityResultContracts;
import androidx.appcompat.app.AppCompatActivity;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collections;
import retrofit2.Call;
@@ -23,11 +27,12 @@ import retrofit2.Response;
public class FotoActivity extends AppCompatActivity {
private ImageView ivFotoComida;
private Button btnTirarFoto, btnAnalisarIA, btnVoltarFoto;
private Button btnTirarFoto, btnGaleria, btnAnalisarIA, btnIrParaChat;
private TextView tvResultadoIA;
private Bitmap imagemCapturada;
private String textoAnalise = "";
// COLA A TUA CHAVE DO OPENROUTER AQUI (Aquela que tiraste sem telemóvel e sem VPN)
// COLA A TUA CHAVE AQUI
private final String MINHA_API_KEY = "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";
@Override
@@ -37,72 +42,114 @@ public class FotoActivity extends AppCompatActivity {
ivFotoComida = findViewById(R.id.ivFotoComida);
btnTirarFoto = findViewById(R.id.btnTirarFoto);
btnGaleria = findViewById(R.id.btnGaleria);
btnAnalisarIA = findViewById(R.id.btnAnalisarIA);
btnIrParaChat = findViewById(R.id.btnIrParaChat);
tvResultadoIA = findViewById(R.id.tvResultadoIA);
btnVoltarFoto = findViewById(R.id.btnVoltarFoto);
ActivityResultLauncher<Intent> cameraLauncher = registerForActivityResult(
ActivityResultLauncher<Intent> camLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Bundle extras = result.getData().getExtras();
imagemCapturada = (Bitmap) extras.get("data");
ivFotoComida.setPadding(0, 0, 0, 0);
ivFotoComida.setImageBitmap(imagemCapturada);
btnTirarFoto.setVisibility(View.GONE);
btnAnalisarIA.setVisibility(View.VISIBLE);
tvResultadoIA.setText("Prato detetado! Clica em Analisar.");
if (extras != null && extras.containsKey("data")) {
imagemCapturada = (Bitmap) extras.get("data");
mostrarImagemPreparada();
}
}
}
);
});
btnTirarFoto.setOnClickListener(v -> cameraLauncher.launch(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)));
ActivityResultLauncher<Intent> galLauncher = registerForActivityResult(
new ActivityResultContracts.StartActivityForResult(),
result -> {
if (result.getResultCode() == RESULT_OK && result.getData() != null) {
Uri uri = result.getData().getData();
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.P) {
ImageDecoder.Source source = ImageDecoder.createSource(this.getContentResolver(), uri);
imagemCapturada = ImageDecoder.decodeBitmap(source);
} else {
imagemCapturada = MediaStore.Images.Media.getBitmap(this.getContentResolver(), uri);
}
mostrarImagemPreparada();
} catch (IOException e) {
tvResultadoIA.setText("Erro ao processar imagem.");
}
}
});
btnAnalisarIA.setOnClickListener(v -> { if (imagemCapturada != null) enviarParaIA(); });
btnVoltarFoto.setOnClickListener(v -> finish());
btnTirarFoto.setOnClickListener(v -> camLauncher.launch(new Intent(MediaStore.ACTION_IMAGE_CAPTURE)));
btnGaleria.setOnClickListener(v -> {
Intent intent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
galLauncher.launch(intent);
});
btnAnalisarIA.setOnClickListener(v -> enviarParaIA());
btnIrParaChat.setOnClickListener(v -> {
Intent intent = new Intent(FotoActivity.this, ChatActivity.class);
intent.putExtra("analise_comida", textoAnalise);
startActivity(intent);
});
findViewById(R.id.btnVoltarFoto).setOnClickListener(v -> finish());
}
private void mostrarImagemPreparada() {
if (imagemCapturada != null) {
ivFotoComida.setVisibility(View.VISIBLE);
ivFotoComida.setPadding(0, 0, 0, 0);
ivFotoComida.setImageBitmap(imagemCapturada);
btnAnalisarIA.setVisibility(View.VISIBLE);
btnIrParaChat.setVisibility(View.GONE);
tvResultadoIA.setText("Pronto para analisar.");
}
}
private void enviarParaIA() {
tvResultadoIA.setText("A procurar servidor livre e a analisar... ⏳");
tvResultadoIA.setText("A processar... ⏳");
btnAnalisarIA.setEnabled(false);
btnIrParaChat.setVisibility(View.GONE);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
imagemCapturada.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
String base64Image = Base64.encodeToString(outputStream.toByteArray(), Base64.NO_WRAP);
ByteArrayOutputStream os = new ByteArrayOutputStream();
imagemCapturada.compress(Bitmap.CompressFormat.JPEG, 50, os);
String base64 = Base64.encodeToString(os.toByteArray(), Base64.NO_WRAP);
String dataUrl = "data:image/jpeg;base64," + base64Image;
String prompt = "Identifica a comida nesta imagem e diz-me as calorias e macronutrientes num pequeno parágrafo.";
String ordemParaIA = "És um nutricionista prático. Identifica a comida e dá os valores de forma SUPER RESUMIDA. " +
"REGRAS: 1. Português de Portugal. 2. SEM asteriscos. 3. Máximo 4 linhas. " +
"Formato exato: \n" +
"Prato: [Nome]\n" +
"Calorias: [Valor] kcal\n" +
"Macros: [X]g Proteína, [X]g Hidratos, [X]g Gordura\n" +
"Dica: [Uma frase curta].";
ContentPart textPart = new ContentPart("text", prompt);
ContentPart imagePart = new ContentPart("image_url", new ImageUrl(dataUrl));
Message message = new Message("user", java.util.Arrays.asList(textPart, imagePart));
AiRequest request = new AiRequest(Collections.singletonList(message));
AiRequest request = new AiRequest(Collections.singletonList(
new Message("user", java.util.Arrays.asList(
new ContentPart("text", ordemParaIA),
new ContentPart("image_url", new ImageUrl("data:image/jpeg;base64," + base64))
))
));
AiApi api = AiConfig.getRetrofit().create(AiApi.class);
api.analisarImagem("Bearer " + MINHA_API_KEY, request).enqueue(new Callback<AiResponse>() {
@Override
public void onResponse(Call<AiResponse> call, Response<AiResponse> response) {
btnAnalisarIA.setEnabled(true);
if (response.isSuccessful() && response.body() != null) {
try {
String resultado = response.body().choices.get(0).message.content;
tvResultadoIA.setText(resultado);
} catch (Exception e) { tvResultadoIA.setText("Erro ao ler texto da IA."); }
} else {
try {
String erroReal = response.errorBody() != null ? response.errorBody().string() : "Vazio";
tvResultadoIA.setText("ERRO: " + response.code() + "\n" + erroReal);
} catch (Exception e) { tvResultadoIA.setText("Erro desconhecido."); }
}
}
@Override
public void onFailure(Call<AiResponse> call, Throwable t) {
btnAnalisarIA.setEnabled(true);
tvResultadoIA.setText("Falha na ligação à Internet.");
}
});
AiConfig.getRetrofit().create(AiApi.class)
.analisarImagem("Bearer " + MINHA_API_KEY, request)
.enqueue(new Callback<AiResponse>() {
@Override
public void onResponse(Call<AiResponse> call, Response<AiResponse> response) {
btnAnalisarIA.setEnabled(true);
if (response.isSuccessful() && response.body() != null) {
try {
String resposta = response.body().choices.get(0).message.content;
textoAnalise = resposta.replace("**", "").replace("*", "");
tvResultadoIA.setText(textoAnalise);
btnIrParaChat.setVisibility(View.VISIBLE);
} catch (Exception e) { tvResultadoIA.setText("Erro na resposta."); }
} else { tvResultadoIA.setText("Erro: " + response.code()); }
}
@Override
public void onFailure(Call<AiResponse> call, Throwable t) {
btnAnalisarIA.setEnabled(true);
tvResultadoIA.setText("Sem internet.");
}
});
}
}