Files
PAP/app/src/main/java/com/example/pap/ChatActivity.java

108 lines
5.0 KiB
Java

package com.example.pap;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.method.ScrollingMovementMethod;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;
import java.util.Collections;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
public class ChatActivity extends AppCompatActivity {
private TextView tvChatLog;
private EditText etMensagem;
private Button btnEnviar;
private TextView btnVoltarChat;
// A TUA CHAVE (cuidado na escola com ela)
private final String MINHA_API_KEY = "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";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_chat);
tvChatLog = findViewById(R.id.tvChatLog);
etMensagem = findViewById(R.id.etMensagem);
btnEnviar = findViewById(R.id.btnEnviarChat);
btnVoltarChat = findViewById(R.id.btnVoltarChat);
// Faz com que o texto do chat consiga rolar se for muito grande
tvChatLog.setMovementMethod(new ScrollingMovementMethod());
btnVoltarChat.setOnClickListener(v -> {
Intent intent = new Intent(ChatActivity.this, HomeActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
});
// Receber a análise da foto (se veio de lá)
String analiseComida = getIntent().getStringExtra("analise_comida");
if (analiseComida != null && !analiseComida.isEmpty()) {
tvChatLog.setText("IA: Analisei o teu prato.\n" + analiseComida + "\n\nO que queres saber mais?");
}
btnEnviar.setOnClickListener(v -> {
String pergunta = etMensagem.getText().toString();
if (!pergunta.isEmpty()) {
tvChatLog.append("\n\nTu: " + pergunta);
etMensagem.setText("");
perguntarIA(pergunta);
}
});
}
private void perguntarIA(String texto) {
tvChatLog.append("\n\nIA: A pensar... ⏳");
btnEnviar.setEnabled(false); // Bloqueia o botão para não haver spam
// 1. ABRIR A GAVETA PARA A IA SABER QUEM ÉS
SharedPreferences prefs = getSharedPreferences("MeusDadosApp", MODE_PRIVATE);
float peso = prefs.getFloat("peso", 0);
float altura = prefs.getFloat("altura", 0);
int idade = prefs.getInt("idade", 20);
// 2. CRIAR O "CÉREBRO" DO NUTRICIONISTA (com os teus dados injetados)
String contextoNutricionista = "És o nutricionista pessoal do utilizador. " +
"Dados do paciente hoje: Peso=" + peso + "kg, Altura=" + altura + "m, Idade=" + idade + " anos. " +
"Se ele perguntar quanta água beber, usa o cálculo de 35ml por cada kg de peso. " +
"Responde SEMPRE de forma muito curta (máximo 3 frases), direta e em Português de Portugal. Nunca uses asteriscos.";
AiRequest request = new AiRequest(java.util.Arrays.asList(
new Message("system", Collections.singletonList(new ContentPart("text", contextoNutricionista))),
new Message("user", Collections.singletonList(new ContentPart("text", texto)))
));
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) {
btnEnviar.setEnabled(true);
if (response.isSuccessful() && response.body() != null) {
String resposta = response.body().choices.get(0).message.content;
String limpa = resposta.replace("**", "").replace("*", "");
String atual = tvChatLog.getText().toString();
tvChatLog.setText(atual.replace("IA: A pensar... ⏳", "IA: " + limpa));
} else {
// Se a API chumbou mas houve resposta (Erro 400, 429...)
String atual = tvChatLog.getText().toString();
tvChatLog.setText(atual.replace("IA: A pensar... ⏳", "IA: Tive um pequeno bloqueio (Erro " + response.code() + "). Tenta outra vez!"));
}
}
@Override
public void onFailure(Call<AiResponse> call, Throwable t) {
btnEnviar.setEnabled(true);
String atual = tvChatLog.getText().toString();
tvChatLog.setText(atual.replace("IA: A pensar... ⏳", "IA: Erro de comunicação (O servidor demorou muito a responder). Tenta novamente."));
}
});
}
}