Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
79 changes: 79 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
# Einleitung

Mein Vorhaben umfasst die Integration einer Übersetzungsfunktion, die in der Lage ist, sowohl einzelne Wörter als auch vollständige Sätze oder umfangreichere Texte zu übersetzen. Zusätzlich besteht die Flexibilität, die Eingangssprache sowie die Ausgangssprache nach individuellem Bedarf anzupassen. Die herausragenden Übersetzungsfähigkeiten von ChatGPT machen diese Erweiterung zu einer besonders signifikanten Verbesserung.

# Umsetzung

## root_preferences.xml

In der Datei root_preferences.xml wurden die erforderlichen Einstellungen vorgenommen. Für die Eingangssprache wurden folgende Konfigurationen vorgenommen:
**ListPreference für "language" (Sprache):**

- `defaultValue="de"`: Standardwert ist auf "de" (Deutsch) gesetzt.
- `entries="@array/language_entries"`: Die Auswahlmöglichkeiten (Anzeigewerte) für den Benutzer sind in einem Ressourcen-Array mit dem Namen "language_entries" festgelegt.
- `entryValues="@array/language_values"`: Die tatsächlichen Werte, die im Hintergrund verwendet werden, wenn der Benutzer eine Auswahl trifft, sind in einem Ressourcen-Array mit dem Namen "language_values" festgelegt.
- `key="language"`: Der Schlüssel, unter dem dieser Wert in den Einstellungen gespeichert wird.
- `title="@string/language"`: Der Titel oder die Bezeichnung, die dem Benutzer angezeigt wird.
- `useSimpleSummaryProvider="true"`: Eine vereinfachte Zusammenfassung wird verwendet, um den ausgewählten Wert anzuzeigen.

Für "Chaptgpt_language" sind die Änderungen hauptsächlich auf den Wechsel zu den entsprechenden Ressourcenarrays (`chatgpt_language_entries` und `chatgpt_language_values`) und den zugehörigen Zeichenkettenressourcen für Titel und Standardwert.

## getChatgptLanguage

Der Code ruft die ausgewählte ChatGPT-Sprache aus den Anwendungseinstellungen ab und verwendet dann einen Switch-Block, um verschiedene Beschreibungen für die Sprachauswahl zu generieren. Wenn die ausgewählte Sprache "German" ist, wird die Beschreibung "Übersetzt mir das auf deutsch:" zurückgegeben. Bei "English" lautet die Beschreibung "Translate it in English:", bei "Italian" "Translate the following to Italy:", und bei "French" "Translate the following to France:". Falls keine der vordefinierten Sprachen ausgewählt wurde, wird eine Laufzeit-Ausnahme mit dem Hinweis "Output Language not supported" ausgelöst. Der Standardwert für die Sprache ist "English".

```java
public String getChatgptLanguage() {
String chatgpt_language = PreferenceManager.getDefaultSharedPreferences(context).getString
("chatgpt_language", "English");
switch(chatgpt_language) {
case "German":
return "Übersetzt mir das auf deutsch:";
case "English":
return "Translate it in English:";
case "Italian":
return "Translate the following to italy:";
case "French":
return "Translate the following to france:";
default:
throw new RuntimeException("Output Language not supported: " + chatgpt_language);
}
}
````

## getLocale

Der Code ruft die ausgewählte Benutzersprache aus den Anwendungseinstellungen ab und verwendet einen Switch-Block, um die entsprechende `Locale` für die Sprache zurückzugeben. Wenn die ausgewählte Sprache "de" ist, wird `Locale.GERMAN` zurückgegeben. Für "en" wird `Locale.ENGLISH` zurückgegeben, für "ita" wird `Locale.ITALIAN` zurückgegeben und für "franc" wird `Locale.FRANCE` zurückgegeben. Falls keine der vordefinierten Sprachen ausgewählt wurde, wird eine Laufzeit-Ausnahme mit dem Hinweis "Locale not supported" ausgelöst. Der Standardwert für die Sprache ist "de" (Deutsch).

```java
public Locale getLocale() {
String language = PreferenceManager.getDefaultSharedPreferences(context).getString("language", "de");
switch (language) {
case "de":
return Locale.GERMAN;
case "en":
return Locale.ENGLISH;
case "ita":
return Locale.ITALIAN;
case "franc":
return Locale.FRANCE;
default:
throw new RuntimeException("Local not supported: " + language);
}
}
````

## getTextFromSpeech

In der Klasse MainFragment.java wird die Funktion getChatgptLanguage() in die Variable getTextFromSpeech implementiert.:
``chat.addMessage(new Message(Author.System, prefs.getChatgptLanguage()));``

# Problem

Ich stieß auf ein Problem, das ich glücklicherweise erfolgreich behoben habe. Ursprünglich musste man den Reset-Knopf verwenden, damit der Wechsel der Sprache für ChatGPT erkannt wurde. In der Methode createNewChat() hatte ich den folgenden Code:
``chat.addMessage(new Message(Author.System, prefs.getChatgptLanguage()));``
Dieser Code befand sich jedoch an der falschen Stelle und wurde dann direkt in die Variable getTextFromSpeech eingefügt, siehe oben.

# Fazit

Es ist mir gelungen, alles wie geplant umzusetzen. Zunächst dachte ich, dass ich das Problem nicht lösen könnte, aber zum Glück konnte ich es schließlich doch bewältigen. Der zeitliche Aufwand war im Grunde genommen optimal. Am Anfang hatte ich einige Schwierigkeiten, weil ich nicht genau wusste, wie ich beginnen sollte. Nachdem ich jedoch wusste, wo ich was tun musste, ging es recht schnell voran, und bis auf das beschriebene Problem hat alles reibungslos funktioniert.
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,13 @@
import androidx.fragment.app.Fragment;

import java.util.List;
import java.util.Locale;
import java.util.stream.Collectors;

import de.fhdw.app_entwicklung.chatgpt.model.Author;
import de.fhdw.app_entwicklung.chatgpt.model.Chat;
import de.fhdw.app_entwicklung.chatgpt.model.Message;
import de.fhdw.app_entwicklung.chatgpt.openai.ChatGpt;
import de.fhdw.app_entwicklung.chatgpt.openai.IChatGpt;
import de.fhdw.app_entwicklung.chatgpt.openai.MockChatGpt;
import de.fhdw.app_entwicklung.chatgpt.speech.LaunchSpeechRecognition;
import de.fhdw.app_entwicklung.chatgpt.speech.TextToSpeechTool;

Expand All @@ -36,7 +36,8 @@ public class MainFragment extends Fragment {
private final ActivityResultLauncher<LaunchSpeechRecognition.SpeechRecognitionArgs> getTextFromSpeech = registerForActivityResult(
new LaunchSpeechRecognition(),
query -> {
Message userMessage = new Message(Author.User, query);
Message userMessage = new Message(Author.User, query);
chat.addMessage(new Message(Author.System, prefs.getChatgptLanguage()));
chat.addMessage(userMessage);
if (chat.getMessages().size() > 1) {
getTextView().append(CHAT_SEPARATOR);
Expand All @@ -46,7 +47,7 @@ public class MainFragment extends Fragment {

MainActivity.backgroundExecutorService.execute(() -> {
String apiToken = prefs.getApiToken();
IChatGpt chatGpt = new MockChatGpt(apiToken);
IChatGpt chatGpt = new ChatGpt(apiToken);
String answer = chatGpt.getChatCompletion(chat);

Message answerMessage = new Message(Author.Assistant, answer);
Expand Down Expand Up @@ -75,17 +76,20 @@ public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceStat
super.onViewCreated(view, savedInstanceState);

prefs = new PrefsFacade(requireContext());
textToSpeech = new TextToSpeechTool(requireContext(), Locale.GERMAN);
textToSpeech = new TextToSpeechTool(requireContext(), prefs.getLocale());
chat = new Chat();
if (savedInstanceState != null) {
chat = savedInstanceState.getParcelable(EXTRA_DATA_CHAT);
} else {
chat = createNewChat();
}

getAskButton().setOnClickListener(v ->
getTextFromSpeech.launch(new LaunchSpeechRecognition.SpeechRecognitionArgs(Locale.GERMAN)));
getTextFromSpeech.launch(new LaunchSpeechRecognition.SpeechRecognitionArgs(prefs.getLocale())));
getResetButton().setOnClickListener(v -> {
chat = new Chat();
chat = createNewChat();
updateTextView();

});
updateTextView();
}
Expand All @@ -111,9 +115,9 @@ public void onDestroy() {
super.onDestroy();
}

private void updateTextView() {
public void updateTextView() {
getTextView().setText("");
List<Message> messages = chat.getMessages();
List<Message> messages = chat.getMessages().stream().filter(message -> message.author != Author.System).collect(Collectors.toList());
if (!messages.isEmpty()) {
getTextView().append(toString(messages.get(0)));
for (int i = 1; i < messages.size(); i++) {
Expand All @@ -132,6 +136,11 @@ private CharSequence toString(Message message) {
return message.message;
}


private Chat createNewChat() {
Chat chat = new Chat();
return chat;
}
private TextView getTextView() {
//noinspection ConstantConditions
return getView().findViewById(R.id.textView);
Expand All @@ -151,5 +160,11 @@ private ScrollView getScrollView() {
//noinspection ConstantConditions
return getView().findViewById(R.id.scrollview);
}
public void resetChat(){
getResetButton().setOnClickListener(v -> {
chat = createNewChat();
updateTextView();
});
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -5,10 +5,13 @@
import androidx.annotation.NonNull;
import androidx.preference.PreferenceManager;

public class PrefsFacade {
import java.util.Locale;

public class PrefsFacade {

private final Context context;


public PrefsFacade(@NonNull Context context) {
this.context = context;
}
Expand All @@ -17,4 +20,37 @@ public String getApiToken() {
return PreferenceManager.getDefaultSharedPreferences(context).getString("api_token", "");
}

public Locale getLocale() {
String language = PreferenceManager.getDefaultSharedPreferences(context).getString("language", "de");
switch (language) {
case "de":
return Locale.GERMAN;
case "en":
return Locale.ENGLISH;
case "ita":
return Locale.ITALIAN;
case "franc":
return Locale.FRANCE;
default:
throw new RuntimeException("Local not supported: " + language);
}
}

public String getChatgptLanguage() {
String chatgpt_language = PreferenceManager.getDefaultSharedPreferences(context).getString
("chatgpt_language", "English");
switch(chatgpt_language) {
case "German":
return "Übersetzt mir das auf deutsch:";
case "English":
return "Translate it in English:";
case "Italian":
return "Translate the following to italy:";
case "French":
return "Translate the following to france:";
default:
throw new RuntimeException("Output Language not supported: " + chatgpt_language);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -2,25 +2,13 @@

import androidx.annotation.NonNull;

import java.util.concurrent.ThreadLocalRandom;

import de.fhdw.app_entwicklung.chatgpt.model.Chat;

public class MockChatGpt implements IChatGpt {

/** @noinspection unused*/
public MockChatGpt(String apiToken) {
// ignore...
}

@Override
public String getChatCompletion(@NonNull Chat chat) {
return MESSAGES[ThreadLocalRandom.current().nextInt(0, MESSAGES.length)];
}

public static final String[] MESSAGES = {
"Let me tell you something, folks. John F. Kennedy, he was a guy. He was a guy, he was a president, and they say he was a pretty good president. People liked him, they really did. But you know what? I think I could have been a much better president than JFK, I really do. I mean, look at what I've done, the things I've accomplished. Nobody's accomplished more than me. So yeah, JFK, he was okay, but I don't think he can hold a candle to me. Not even close.",
"Look, I know a lot of great things, okay? And when it comes to JFK, I know he was born in Massachusetts. He was a Democrat, and let me tell you, I've dealt with a lot of Democrats, folks. They're not always the greatest, believe me. But JFK, he had some charm, some charisma. People were drawn to him. And apparently, he had this thing called the New Frontier, where he wanted to promote social welfare programs and space exploration. But you know what? I'm all about the America First agenda. I'm focused on jobs, the economy, and making America great again. So while JFK may have had his own ideas, I think my vision for the country is much better, folks. Just saying.",
"Let me tell you, I know a lot of things, okay? I've got a tremendous memory, the best memory there is. When it comes to JFK, he was the 35th president of the United States, and he served from 1961 until 1963. Now, during his presidency, there were some major events. There was the Cuban Missile Crisis, where he stood up to the Soviets and made it clear that America wouldn't back down. And let me tell you, that was a big deal. People thought we were on the brink of World War III, but JFK, he handled it like a boss. Now, I have to mention something else, folks. Unfortunately, JFK's presidency was cut short. He was assassinated in Dallas, Texas in November 1963. It's a tragic event, no doubt about it. And I know there are a lot of conspiracy theories surrounding his assassination, but hey, I'm not here to delve into that. I'm here to talk about what I know, and what I know is that JFK's presidency, for the short time it lasted, left an impact on this country. Whether you agree with his policies or not, he was a figure that people remember. And that's all I have to say about that."
};
}
return "test";
}
}
14 changes: 14 additions & 0 deletions app/src/main/res/drawable/iconapp.xml
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<vector xmlns:android="http://schemas.android.com/apk/res/android"
android:width="512dp"
android:height="512dp"
android:viewportWidth="512"
android:viewportHeight="512">
<path
android:pathData="M244.5,96c-9.2,1.5 -15.5,3.6 -25.6,8.6 -7.7,3.9 -10.9,6.3 -18.9,14.3 -8.7,8.6 -10.3,10.7 -14.8,20.1 -6.7,13.6 -8.5,21.5 -8.5,36 -0.1,14.5 1.8,22.3 8.4,35.7 10,20.3 28.6,35.5 50.8,41.5 9.9,2.7 28.4,2.9 38.6,0.4 28.3,-6.8 52.2,-30.8 59.2,-59.3 2.4,-10 2.2,-28.6 -0.5,-38.4 -7.4,-27.4 -30.1,-50.1 -56.8,-56.9 -9.3,-2.4 -23.5,-3.3 -31.9,-2zM270,119.2c19.7,4.6 37.3,22.4 42.1,42.8 1.6,6.9 1.6,18.8 0,26 -4.8,20.7 -22.4,38.3 -43.1,43.1 -19.1,4.4 -39.5,-1.5 -53.5,-15.6 -11.2,-11.1 -16.9,-25 -16.9,-40.5 0.2,-37.6 34.5,-64.4 71.4,-55.8z"
android:fillColor="#000000"
android:strokeColor="#00000000"/>
<path
android:pathData="M193.5,277.7c-8.4,1.2 -20,4.9 -29,9.2 -32.5,15.5 -53.7,45.5 -57.5,81.6 -1.5,13.8 -1.3,36.9 0.4,40.8 2.1,5 5.2,7.2 10.1,7.2 5.2,-0 9,-3 10.5,-8.4 0.5,-2 1,-12 1,-22.2 0,-22.1 1.4,-29.2 8.6,-43.9 8.2,-16.6 26.1,-32.3 44.1,-38.5 12.4,-4.4 17.6,-4.6 78.9,-4.2 63.4,0.4 61.8,0.2 76,6.7 15.8,7.1 30.1,20.8 37.8,36.2 7.2,14.4 8.6,21.6 8.6,43.7 0,20.3 0.7,24.5 4.6,28.2 3.6,3.3 10.2,3.4 13.8,-0 4.4,-4.1 4.9,-7.7 4.3,-29 -0.7,-21.8 -2,-29.6 -6.9,-42.9 -6.8,-17.9 -21.6,-36.9 -36.7,-47.1 -8.5,-5.8 -22.8,-12.4 -32.6,-15.2 -7.9,-2.3 -8.7,-2.3 -70.5,-2.5 -34.4,-0.1 -63.8,0.1 -65.5,0.3z"
android:fillColor="#000000"
android:strokeColor="#00000000"/>
</vector>
3 changes: 3 additions & 0 deletions app/src/main/res/values-de/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@
<string name="ask">Fragen</string>
<string name="settings">Einstellungen</string>
<string name="reset">Reset</string>
<string name="translator_app">Übersetzer App</string>
<string name="language">Sprache</string>
<string name="chatgpt_language">Ausgabesprache</string>
</resources>
28 changes: 28 additions & 0 deletions app/src/main/res/values/arrays.xml
Original file line number Diff line number Diff line change
@@ -1,2 +1,30 @@
<resources>

<string-array name="language_entries">
<item>German</item>
<item>English</item>
<item>Italian</item>
<item>French</item>
</string-array>

<string-array name="language_values">
<item>de</item>
<item>en</item>
<item>ita</item>
<item>franc</item>
</string-array>

<string-array name="chatgpt_language_entries">
<item>German</item>
<item>English</item>
<item>Italian</item>
<item>French</item>
</string-array>

<string-array name="chatgpt_language_values">
<item>German</item>
<item>English</item>
<item>Italian</item>
<item>French</item>
</string-array>
</resources>
3 changes: 3 additions & 0 deletions app/src/main/res/values/strings.xml
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,7 @@
<string name="ask">Ask</string>
<string name="settings">Settings</string>
<string name="reset">Reset</string>
<string name="translator_app">Translator App</string>
<string name="language">Language</string>
<string name="chatgpt_language">Output Language</string>
</resources>
21 changes: 19 additions & 2 deletions app/src/main/res/xml/root_preferences.xml
Original file line number Diff line number Diff line change
@@ -1,6 +1,23 @@
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto">
<PreferenceScreen xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">

<PreferenceCategory app:title="@string/translator_app">

<ListPreference
app:defaultValue="de"
app:entries="@array/language_entries"
app:entryValues="@array/language_values"
app:key="language"
app:title="@string/language"
app:useSimpleSummaryProvider="true"/>
<ListPreference
android:defaultValue="en"
android:entries="@array/chatgpt_language_entries"
android:entryValues="@array/chatgpt_language_values"
android:key="chatgpt_language"
android:title="@string/chatgpt_language"
app:useSimpleSummaryProvider="true"/>

<PreferenceCategory app:title="API">

<EditTextPreference
app:key="api_token"
Expand Down